UNPKG

@ogcio/o11y-sdk-node

Version:

Opentelemetry standard instrumentation SDK for NodeJS based project

36 lines (35 loc) 1.23 kB
import { SpanStatusCode } from "@opentelemetry/api"; /** * Generates a function wrapping a given Callable `fn` into an error handling block. * Setting Span status and recording any caught exception before bubbling it up. * * Marks the span as ended once the provided callable has ended or an error has been caught. * * @returns {Promise<T>} where T is the type returned by the Callable. * @throws any error thrown by the original Callable `fn` provided. */ export function selfContainedSpanHandlerGenerator(fn) { return async (span) => { try { const fnResult = await fn(span); span.setStatus({ code: SpanStatusCode.OK }); return fnResult; } catch (err) { if (err instanceof Error) { span.recordException(err); span.setStatus({ code: SpanStatusCode.ERROR, message: err.message }); throw err; } span.recordException({ message: JSON.stringify(err) }); span.setStatus({ code: SpanStatusCode.ERROR, message: JSON.stringify(err), }); throw err; } finally { span.end(); } }; }