From 616c12b157f7736e9fd45cd38bf9a4c21c11e140 Mon Sep 17 00:00:00 2001 From: Tine Jozelj Date: Fri, 25 Mar 2022 12:07:03 +0100 Subject: [PATCH] fix(tracing): record exception and set correct span status As mentioned in https://opentelemetry.io/docs/instrumentation/js/instrumentation/#recording-exceptions --- src/tracing/decorators/span.ts | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/src/tracing/decorators/span.ts b/src/tracing/decorators/span.ts index 810f5a8..f32cbef 100644 --- a/src/tracing/decorators/span.ts +++ b/src/tracing/decorators/span.ts @@ -1,4 +1,9 @@ -import { trace } from '@opentelemetry/api'; +import { Span as ApiSpan, SpanStatusCode, trace } from '@opentelemetry/api'; + +const recordException = (span: ApiSpan, error: any) => { + span.recordException(error); + span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); +}; export function Span(name?: string) { return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => { @@ -10,13 +15,27 @@ export function Span(name?: string) { return tracer.startActiveSpan(spanName, span => { if (method.constructor.name === 'AsyncFunction') { - return method.apply(this, args).finally(() => { - span.end(); - }); + return method + .apply(this, args) + .catch(error => { + recordException(span, error); + // Throw error to propagate it further + throw error; + }) + .finally(() => { + span.end(); + }); + } + + try { + return method.apply(this, args); + } catch (error) { + recordException(span, error); + // Throw error to propagate it further + throw error; + } finally { + span.end(); } - const result = method.apply(this, args); - span.end(); - return result; }); }; };