Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export {
export { safeSetSpanJSONAttributes } from './tracing/spans/captureSpan';
export { isSentryRequestUrl } from './utils/isSentryRequestUrl';
export { handleCallbackErrors } from './utils/handleCallbackErrors';
export { safeCallback } from './utils/safeCallback';
export { parameterize, fmt } from './utils/parameterize';
export type { HandleTunnelRequestOptions } from './utils/tunnel';
export { handleTunnelRequest } from './utils/tunnel';
Expand Down
43 changes: 22 additions & 21 deletions packages/core/src/tracing/spans/beforeSendSpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { DEBUG_BUILD } from '../../debug-build';
import type { BeforeSendStaticSpanCallback, BeforeSendStreamedSpanCallback } from '../../types/options';
import type { SpanJSON, StreamedSpanJSON } from '../../types/span';
import { addNonEnumerableProperty } from '../../utils/object';
import { consoleSandbox, debug } from '../../utils/debug-logger';
import { consoleSandbox } from '../../utils/debug-logger';
import { safeCallback } from '../../utils/safeCallback';

/**
* A wrapper to use the static, transaction-based span format in your `beforeSendSpan` callback.
Expand Down Expand Up @@ -64,25 +65,25 @@ export function applyBeforeSendSpanCallback<T extends StreamedSpanJSON | SpanJSO
span: T,
beforeSendSpan: (span: T) => T,
): T {
try {
const modifedSpan = beforeSendSpan(span);
if (!modifedSpan) {
if (!hasShownSpanDropWarning) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.',
);
});
hasShownSpanDropWarning = true;
}
return span;
}
return modifedSpan;
} catch (error) {
// Spans are captured synchronously when they end, so a throwing callback would otherwise
// propagate into whatever user code ended the span.
DEBUG_BUILD && debug.error('The `beforeSendSpan` callback threw an error, sending the span unmodified:', error);
return span;
// Spans are captured synchronously when they end, so a throwing callback would otherwise
// propagate into whatever user code ended the span.
const modifiedSpan = safeCallback(
DEBUG_BUILD ? 'The `beforeSendSpan` callback threw an error, sending the span unmodified:' : '',
() => beforeSendSpan(span),
() => span,
);
if (modifiedSpan) {
return modifiedSpan;
}

if (!hasShownSpanDropWarning) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unrelated to this PR, but we can possibly remove this warning (safe some bytes), this has been this way for some time 🤔 or at least make it a debug.warn gated by the debug flag so you can shake it out?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah i think we can remove it tbh. has been like this since v9 and the type doesn't allow it anyway.

consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.',
);
});
hasShownSpanDropWarning = true;
}
return span;
}
35 changes: 35 additions & 0 deletions packages/core/src/utils/safeCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { DEBUG_BUILD } from '../debug-build';
import { debug } from './debug-logger';
import { isThenable } from './is';

/**
* Invokes a user-provided callback (e.g. `beforeSend`, `tracesSampler`, an integration hook) so that
* neither a synchronous throw nor a rejected promise escapes into the caller. On failure the error is
* logged and `fallback(error)` supplies the result instead.
*
* Not for `startSpan` bodies: those must re-throw and are handled by `handleCallbackErrors`.
*
* @param message - Logged via `debug.error` together with the error. Pass it as `DEBUG_BUILD ? '...' : ''`
* so the string is tree-shaken from non-debug bundles.
* @param fn - Invokes the callback.
* @param fallback - Produces the result to use when the callback throws or rejects.
*/
export function safeCallback<T>(message: string, fn: () => T, fallback: (error: unknown) => T): T {
let result: T;
try {
result = fn();
} catch (error) {
return recover(message, error, fallback);
}

if (isThenable(result)) {
return result.then(undefined, (error: unknown) => recover(message, error, fallback)) as T;
}

return result;
}

function recover<T>(message: string, error: unknown, fallback: (error: unknown) => T): T {
DEBUG_BUILD && debug.error(message, error);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the flag is correct here but the bot review is right: We no longer tree-shake out the actual string passed to this function if DEBUG_BUILD is false. We can still add a ternary to the call-sitest to enable tree shaking, something like

safeCallback(DEBUG_BUILD ? 'full warning/error message' : '', () => {}, () => {})

return fallback(error);
Comment thread
cursor[bot] marked this conversation as resolved.
}
70 changes: 70 additions & 0 deletions packages/core/test/lib/utils/safeCallback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { debug } from '../../../src/utils/debug-logger';
import { safeCallback } from '../../../src/utils/safeCallback';

describe('safeCallback', () => {
const debugErrorSpy = vi.spyOn(debug, 'error').mockImplementation(() => undefined);

afterEach(() => {
debugErrorSpy.mockClear();
});

it('returns the result of a sync callback', () => {
const fallback = vi.fn(() => 'fallback');

expect(safeCallback('callback threw:', () => 'value', fallback)).toBe('value');
expect(fallback).not.toHaveBeenCalled();
expect(debugErrorSpy).not.toHaveBeenCalled();
});

it('returns the fallback and logs when a sync callback throws', () => {
const error = new Error('boom');
const fallback = vi.fn(() => 'fallback');

expect(
safeCallback(
'callback threw:',
() => {
throw error;
},
fallback,
),
).toBe('fallback');
expect(fallback).toHaveBeenCalledWith(error);
expect(debugErrorSpy).toHaveBeenCalledWith('callback threw:', error);
});

it('resolves to the result of an async callback', async () => {
const fallback = vi.fn(async () => 'fallback');

const result = safeCallback('callback threw:', async () => 'value', fallback);

expect(result).toBeInstanceOf(Promise);
await expect(result).resolves.toBe('value');
expect(fallback).not.toHaveBeenCalled();
expect(debugErrorSpy).not.toHaveBeenCalled();
});

it('resolves to the fallback and logs when an async callback rejects', async () => {
const error = new Error('boom');
const fallback = vi.fn(async () => 'fallback');

const result = safeCallback('callback threw:', () => Promise.reject(error), fallback);

await expect(result).resolves.toBe('fallback');
expect(fallback).toHaveBeenCalledWith(error);
expect(debugErrorSpy).toHaveBeenCalledWith('callback threw:', error);
});

it('does not treat non-thenable objects as promises', () => {
const value = { then: 'not a function' };

expect(
safeCallback(
'callback threw:',
() => value,
() => ({ then: 'fallback' }),
),
).toBe(value);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
isTracingSuppressed,
LRUMap,
parseUrl,
safeCallback,
SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SPAN_STATUS_ERROR,
Expand Down Expand Up @@ -113,16 +114,6 @@ export function instrumentUndici(config: NodeFetchOptions = {}): void {
subscribeToChannel('undici:request:error', message => onError(message as RequestErrorMessage));
}

/** Replaces OTel's `safeExecuteInTheMiddle`: run `fn`, route any error to `onError`, and swallow it. */
function safeExecute<T>(fn: () => T, onError: (error: unknown) => void): T | undefined {
try {
return fn();
} catch (error) {
onError(error);
return undefined;
}
}

function subscribeToChannel(
diagnosticChannel: string,
onMessage: (message: unknown, name: string | symbol) => void,
Expand Down Expand Up @@ -180,9 +171,10 @@ function parseRequestHeaders(request: UndiciRequest): Map<string, string | strin
function onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage): void {
const url = getAbsoluteUrl(request.origin, request.path);

const ignoredByCallback = safeExecute(
const ignoredByCallback = safeCallback(
DEBUG_BUILD ? 'The `ignoreOutgoingRequests` callback threw an error, not ignoring the request:' : '',
() => !!config.ignoreOutgoingRequests?.(url),
e => e && DEBUG_BUILD && debug.error('caught ignoreOutgoingRequests error: ', e),
() => false,
);

// Breadcrumbs & span-less trace propagation are additionally skipped when tracing is suppressed.
Expand Down Expand Up @@ -288,9 +280,10 @@ function onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage)
});

// Execute the request hook if defined
safeExecute(
safeCallback(
DEBUG_BUILD ? 'The `requestHook` callback threw an error:' : '',
() => config.requestHook?.(span, request),
e => e && DEBUG_BUILD && debug.error('caught requestHook error: ', e),
() => undefined,
);

// Context propagation goes last so no hook can tamper the propagation headers.
Expand Down Expand Up @@ -356,9 +349,10 @@ function onResponseHeaders(config: NodeFetchOptions, { request, response }: Resp
};

// Execute the response hook if defined
safeExecute(
safeCallback(
DEBUG_BUILD ? 'The `responseHook` callback threw an error:' : '',
() => config.responseHook?.(span, { request, response }),
e => e && DEBUG_BUILD && debug.error('caught responseHook error: ', e),
() => undefined,
);

if (config.headersToSpanAttributes?.responseHeaders) {
Expand Down
Loading