Skip to content

Commit 0d93cf6

Browse files
committed
fix(instrumentation-express): Finish spans after execution
1 parent 91c9089 commit 0d93cf6

File tree

2 files changed

+322
-109
lines changed

2 files changed

+322
-109
lines changed

plugins/node/opentelemetry-instrumentation-express/src/instrumentation.ts

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -234,13 +234,6 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
234234
}
235235

236236
let spanHasEnded = false;
237-
if (
238-
metadata.attributes[AttributeNames.EXPRESS_TYPE] !==
239-
ExpressLayerType.MIDDLEWARE
240-
) {
241-
span.end();
242-
spanHasEnded = true;
243-
}
244237
// listener for response.on('finish')
245238
const onResponseFinish = () => {
246239
if (spanHasEnded === false) {
@@ -269,16 +262,28 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
269262
});
270263
}
271264

272-
if (spanHasEnded === false) {
273-
spanHasEnded = true;
274-
req.res?.removeListener('finish', onResponseFinish);
275-
span.end();
276-
}
277265
if (!(req.route && isError)) {
278266
(req[_LAYERS_STORE_PROPERTY] as string[]).pop();
279267
}
280268
const callback = args[callbackIdx] as Function;
281-
return callback.apply(this, arguments);
269+
270+
try {
271+
return callback.apply(this, arguments);
272+
} catch (anyError) {
273+
const [error, message] = asErrorAndMessage(anyError);
274+
span.recordException(error);
275+
span.setStatus({
276+
code: SpanStatusCode.ERROR,
277+
message,
278+
});
279+
throw anyError;
280+
} finally {
281+
if (!spanHasEnded) {
282+
spanHasEnded = true;
283+
req.res?.removeListener('finish', onResponseFinish);
284+
span.end();
285+
}
286+
}
282287
};
283288
}
284289

0 commit comments

Comments
 (0)