Skip to content

Commit a08cae2

Browse files
authored
fix(node): Ensure adding sentry-trace and baggage headers via SentryHttpInstrumentation doesn't crash (#16473)
On Node > 22.10.0, when spans are off, the `SentryHttpInstrumentation` attempts adding `sentry-trace` and `baggage` headers to requests. Due to race-conditions, this can error in cases where the request was already sent/finished prior to setting the headers. This fix prevents this by wrapping the logic in a try/catch. Fixes: #16438
1 parent ac22be2 commit a08cae2

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

packages/node/src/integrations/http/SentryHttpInstrumentation.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
getSanitizedUrlString,
2121
getTraceData,
2222
httpRequestToRequestData,
23+
isError,
2324
logger,
2425
LRUMap,
2526
parseUrl,
@@ -262,15 +263,34 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
262263

263264
// We do not want to overwrite existing header here, if it was already set
264265
if (sentryTrace && !request.getHeader('sentry-trace')) {
265-
request.setHeader('sentry-trace', sentryTrace);
266-
logger.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
266+
try {
267+
request.setHeader('sentry-trace', sentryTrace);
268+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
269+
} catch (error) {
270+
DEBUG_BUILD &&
271+
logger.error(
272+
INSTRUMENTATION_NAME,
273+
'Failed to add sentry-trace header to outgoing request:',
274+
isError(error) ? error.message : 'Unknown error',
275+
);
276+
}
267277
}
268278

269279
if (baggage) {
270280
// For baggage, we make sure to merge this into a possibly existing header
271281
const newBaggage = mergeBaggageHeaders(request.getHeader('baggage'), baggage);
272282
if (newBaggage) {
273-
request.setHeader('baggage', newBaggage);
283+
try {
284+
request.setHeader('baggage', newBaggage);
285+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added baggage header to outgoing request');
286+
} catch (error) {
287+
DEBUG_BUILD &&
288+
logger.error(
289+
INSTRUMENTATION_NAME,
290+
'Failed to add baggage header to outgoing request:',
291+
isError(error) ? error.message : 'Unknown error',
292+
);
293+
}
274294
}
275295
}
276296
}

0 commit comments

Comments
 (0)