Skip to content

Commit db5cf13

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

File tree

2 files changed

+316
-109
lines changed

2 files changed

+316
-109
lines changed

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

Lines changed: 12 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,22 @@ 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+
throw anyError;
274+
} finally {
275+
if (!spanHasEnded) {
276+
spanHasEnded = true;
277+
req.res?.removeListener('finish', onResponseFinish);
278+
span.end();
279+
}
280+
}
282281
};
283282
}
284283

0 commit comments

Comments
 (0)