Skip to content

feat(v9/react-router): Add createSentryHandleError #17244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 31, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context, GLOBAL_OBJ, flush, logger, vercelWaitUntil } from '@sentry/core';
import { Context, flushIfServerless } from '@sentry/core';
import * as SentryNode from '@sentry/node';
import { H3Error } from 'h3';
import type { CapturedErrorContext } from 'nitropack';
Expand Down Expand Up @@ -53,31 +53,3 @@ function extractErrorContext(errorContext: CapturedErrorContext): Context {

return ctx;
}

async function flushIfServerless(): Promise<void> {
const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.VERCEL ||
!!process.env.NETLIFY;

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
vercelWaitUntil(flushWithTimeout());
} else if (isServerless) {
await flushWithTimeout();
}
}

async function flushWithTimeout(): Promise<void> {
const sentryClient = SentryNode.getClient();
const isDebug = sentryClient ? sentryClient.getOptions().debug : false;

try {
isDebug && logger.log('Flushing events...');
await flush(2000);
isDebug && logger.log('Done flushing events');
} catch (e) {
isDebug && logger.log('Error while flushing events:\n', e);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,4 @@ const handleRequest = Sentry.createSentryHandleRequest({

export default handleRequest;

export const handleError: HandleErrorFunction = (error, { request }) => {
// React Router may abort some interrupted requests, don't log those
if (!request.signal.aborted) {
Sentry.captureException(error);

// make sure to still log the error so you can see it
console.error(error);
}
};
export const handleError: HandleErrorFunction = Sentry.createSentryHandleError({ logErrors: true });
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down Expand Up @@ -67,7 +68,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,4 @@ const handleRequest = Sentry.createSentryHandleRequest({

export default handleRequest;

export const handleError: HandleErrorFunction = (error, { request }) => {
// React Router may abort some interrupted requests, don't log those
if (!request.signal.aborted) {
Sentry.captureException(error);

// make sure to still log the error so you can see it
console.error(error);
}
};
export const handleError: HandleErrorFunction = Sentry.createSentryHandleError({ logErrors: true });
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down Expand Up @@ -67,7 +68,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,4 @@ const handleRequest = Sentry.createSentryHandleRequest({

export default handleRequest;

export const handleError: HandleErrorFunction = (error, { request }) => {
// React Router may abort some interrupted requests, don't log those
if (!request.signal.aborted) {
Sentry.captureException(error);

// make sure to still log the error so you can see it
console.error(error);
}
};
export const handleError: HandleErrorFunction = Sentry.createSentryHandleError({ logErrors: true });
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down Expand Up @@ -67,7 +68,8 @@ test.describe('server-side errors', () => {
type: 'Error',
value: errorMessage,
mechanism: {
handled: true,
handled: false,
type: 'react-router',
},
},
],
Expand Down
15 changes: 2 additions & 13 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import type { RequestEventData, Scope, SpanAttributes } from '@sentry/core';
import {
addNonEnumerableProperty,
debug,
extractQueryParamsFromUrl,
flushIfServerless,
objectify,
stripUrlQueryAndFragment,
vercelWaitUntil,
winterCGRequestToRequestData,
} from '@sentry/core';
import {
captureException,
continueTrace,
flush,
getActiveSpan,
getClient,
getCurrentScope,
Expand Down Expand Up @@ -240,16 +238,7 @@ async function instrumentRequest(
);
return res;
} finally {
vercelWaitUntil(
(async () => {
// Flushes pending Sentry events with a 2-second timeout and in a way that cannot create unhandled promise rejections.
try {
await flush(2000);
} catch (e) {
debug.log('Error while flushing events:\n', e);
}
})(),
);
await flushIfServerless();
}
// TODO: flush if serverless (first extract function)
},
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ export { callFrameToStackFrame, watchdogTimer } from './utils/anr';
export { LRUMap } from './utils/lru';
export { generateTraceId, generateSpanId } from './utils/propagationContext';
export { vercelWaitUntil } from './utils/vercelWaitUntil';
export { flushIfServerless } from './utils/flushIfServerless';
export { SDK_VERSION } from './utils/version';
export { getDebugImagesForResources, getFilenameToDebugIdMap } from './utils/debug-ids';
export { escapeStringForRegex } from './vendor/escapeStringForRegex';
Expand Down
77 changes: 77 additions & 0 deletions packages/core/src/utils/flushIfServerless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { flush } from '../exports';
import { debug } from './debug-logger';
import { vercelWaitUntil } from './vercelWaitUntil';
import { GLOBAL_OBJ } from './worldwide';

type MinimalCloudflareContext = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitUntil(promise: Promise<any>): void;
};

async function flushWithTimeout(timeout: number): Promise<void> {
try {
debug.log('Flushing events...');
await flush(timeout);
debug.log('Done flushing events');
} catch (e) {
debug.log('Error while flushing events:\n', e);
}
}

/**
* Flushes the event queue with a timeout in serverless environments to ensure that events are sent to Sentry before the
* serverless function execution ends.
*
* The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.
*
* This function is aware of the following serverless platforms:
* - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).
* If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).
* - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.
* - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables
* and uses a regular `await flush()`.
*
* @internal This function is supposed for internal Sentry SDK usage only.
* @hidden
*/
export async function flushIfServerless(
params: // eslint-disable-next-line @typescript-eslint/no-explicit-any
| { timeout?: number; cloudflareWaitUntil?: (task: Promise<any>) => void }
| { timeout?: number; cloudflareCtx?: MinimalCloudflareContext } = {},
): Promise<void> {
const { timeout = 2000 } = params;

if ('cloudflareWaitUntil' in params && typeof params?.cloudflareWaitUntil === 'function') {
params.cloudflareWaitUntil(flushWithTimeout(timeout));
return;
}

if ('cloudflareCtx' in params && typeof params.cloudflareCtx?.waitUntil === 'function') {
params.cloudflareCtx.waitUntil(flushWithTimeout(timeout));
return;
}

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
// Vercel has a waitUntil equivalent that works without execution context
vercelWaitUntil(flushWithTimeout(timeout));
return;
}

if (typeof process === 'undefined') {
return;
}

const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.K_SERVICE || // Google Cloud Run
!!process.env.CF_PAGES || // Cloudflare Pages
!!process.env.VERCEL ||
!!process.env.NETLIFY;

if (isServerless) {
// Use regular flush for environments without a generic waitUntil mechanism
await flushWithTimeout(timeout);
}
}
128 changes: 128 additions & 0 deletions packages/core/test/lib/utils/flushIfServerless.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as flushModule from '../../../src/exports';
import { flushIfServerless } from '../../../src/utils/flushIfServerless';
import * as vercelWaitUntilModule from '../../../src/utils/vercelWaitUntil';
import { GLOBAL_OBJ } from '../../../src/utils/worldwide';

describe('flushIfServerless', () => {
let originalProcess: typeof process;

beforeEach(() => {
vi.resetAllMocks();
originalProcess = global.process;
});

afterEach(() => {
vi.restoreAllMocks();
});

test('should bind context (preserve `this`) when calling waitUntil from the Cloudflare execution context', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

// Mock Cloudflare context with `waitUntil` (which should be called if `this` is bound correctly)
const mockCloudflareCtx = {
contextData: 'test-data',
waitUntil: function (promise: Promise<unknown>) {
// This will fail if 'this' is not bound correctly
expect(this.contextData).toBe('test-data');
return promise;
},
};

const waitUntilSpy = vi.spyOn(mockCloudflareCtx, 'waitUntil');

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(waitUntilSpy).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should use cloudflare waitUntil when valid cloudflare context is provided', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx, timeout: 5000 });

expect(mockCloudflareCtx.waitUntil).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(5000);
});

test('should use cloudflare waitUntil when Cloudflare `waitUntil` is provided', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareWaitUntil: mockCloudflareCtx.waitUntil, timeout: 5000 });

expect(mockCloudflareCtx.waitUntil).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(5000);
});

test('should ignore cloudflare context when waitUntil is not a function (and use Vercel waitUntil instead)', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const vercelWaitUntilSpy = vi.spyOn(vercelWaitUntilModule, 'vercelWaitUntil').mockImplementation(() => {});

// Mock Vercel environment
// @ts-expect-error This is not typed
GLOBAL_OBJ[Symbol.for('@vercel/request-context')] = { get: () => ({ waitUntil: vi.fn() }) };

const mockCloudflareCtx = {
waitUntil: 'not-a-function', // Invalid waitUntil
};

// @ts-expect-error Using the wrong type here on purpose
await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(vercelWaitUntilSpy).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should handle multiple serverless environment variables simultaneously', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

global.process = {
...originalProcess,
env: {
...originalProcess.env,
LAMBDA_TASK_ROOT: '/var/task',
VERCEL: '1',
NETLIFY: 'true',
CF_PAGES: '1',
},
};

await flushIfServerless({ timeout: 4000 });

expect(flushMock).toHaveBeenCalledWith(4000);
});

test('should use default timeout when not specified', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should handle zero timeout value', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

global.process = {
...originalProcess,
env: {
...originalProcess.env,
LAMBDA_TASK_ROOT: '/var/task',
},
};

await flushIfServerless({ timeout: 0 });

expect(flushMock).toHaveBeenCalledWith(0);
});
});
Loading
Loading