UNPKG

@sentry/core

Version:
58 lines (57 loc) • 2.69 kB
import { getTraceContextFromScope } from "../currentScopes.js"; import { isPrimitive } from "./is.js"; import { spanIsSampled, spanToTraceContext } from "./spanUtils.js"; // src/utils/errorSpanAttribution.ts /** * The trace context of the span an error escaped, keyed by the error itself. * * We store the trace context rather than the span because that is the shape we apply to the event * later, and it snapshots the span as it failed instead of reading it back once it has ended. */ const escapedSpanTraceContexts = /* @__PURE__ */ new WeakMap(); /** * A `WeakMap` can only be keyed by an object, so an error thrown as a primitive (`throw 'boom'`) * has nothing we can hang the span on and is left unattributed. */ function toWeakMapKey(error) { return isPrimitive(error) ? void 0 : error; } /** * Remember which span an error escaped, so a later `captureException` can attribute the error to * the span that actually failed instead of whichever span happens to be active at capture time. * * The first span to see the error wins: as an error unwinds through nested spans, the innermost * one is the one that failed. Unsampled spans are skipped because they are never sent, so their * span id would point at a span that does not exist. Sampling rather than `isRecording()` is what * matters here: a span ended before the error escaped it, which is the norm for `startSpanManual`, * has stopped recording but is still sent. */ function recordEscapedErrorSpan(error, span) { const key = toWeakMapKey(error); if (!key || !spanIsSampled(span) || escapedSpanTraceContexts.has(key)) return; escapedSpanTraceContexts.set(key, spanToTraceContext(span)); } /** * Attribute an error event to the span the error escaped, if we recorded one. * * This only applies within the error's own trace. The stored span id is meaningless in another * trace, and the event's dynamic sampling context (which the envelope header is built from) is * derived from the root span of the trace the event is already on. Rewriting the trace id here * would leave the envelope header and body naming different traces. */ function applyEscapedErrorSpanToEvent(event, hint, scope) { const key = toWeakMapKey(hint.originalException); const traceContext = key && escapedSpanTraceContexts.get(key); if (!traceContext) return; const eventTraceContext = event.contexts?.trace; if ((eventTraceContext?.trace_id ?? (scope && getTraceContextFromScope(scope).trace_id)) !== traceContext.trace_id) return; event.contexts = { ...event.contexts, trace: { ...eventTraceContext, ...traceContext } }; } export { applyEscapedErrorSpanToEvent, recordEscapedErrorSpan }; //# sourceMappingURL=errorSpanAttribution.js.map