diff --git a/plugins/catalog-backend/src/util/opentelemetry.ts b/plugins/catalog-backend/src/util/opentelemetry.ts index c2df008452..3fb83d7909 100644 --- a/plugins/catalog-backend/src/util/opentelemetry.ts +++ b/plugins/catalog-backend/src/util/opentelemetry.ts @@ -50,23 +50,38 @@ const onException = (e: Error, span: Span) => { }); }; +function isPromiseLike(obj: PromiseLike | S): obj is PromiseLike { + return ( + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + 'then' in obj && + typeof obj.then === 'function' + ); +} + function handleFn ReturnType>( span: Span, fn: F, ): ReturnType { try { - const ret = fn(span) as Promise>; + const ret = fn(span); + // if fn is an async function attach a recordException and spanEnd callback to the promise - if (typeof ret.then === 'function' && typeof ret.catch === 'function') { - return ret - .catch((e: Error) => { + if (isPromiseLike(ret)) { + ret.then( + () => { + span.end(); + }, + e => { onException(e, span); - throw e; - }) - .finally(() => span.end()) as ReturnType; + span.end(); + }, + ); + } else { + span.end(); } - span.end(); - return ret as ReturnType; + + return ret; } catch (e) { onException(e, span); span.end();