Skip to content

fix(cloudflare): Capture exceptions thrown in hono #16355

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 4 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
26 changes: 26 additions & 0 deletions packages/cloudflare/src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { init } from './sdk';
* @param handler {ExportedHandler} The handler to wrap.
* @returns The wrapped handler.
*/
// eslint-disable-next-line complexity
export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown>(
optionsCallback: (env: Env) => CloudflareOptions,
handler: ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>,
Expand All @@ -47,6 +48,31 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
markAsInstrumented(handler.fetch);
}

/* hono does not reach the catch block of the fetch handler and captureException needs to be called in the hono errorHandler */
if (
'onError' in handler &&
'errorHandler' in handler &&
typeof handler.errorHandler === 'function' &&
Copy link
Member

Choose a reason for hiding this comment

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

So this is always defined right? We don't need to create one for a user if it's not defined?

Copy link
Member Author

Choose a reason for hiding this comment

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

!isInstrumented(handler.errorHandler)
) {
handler.errorHandler = new Proxy(handler.errorHandler, {
apply(target, thisArg, args) {
const [err] = args;

captureException(err, {
mechanism: {
handled: false,
type: 'cloudflare',
},
});

return Reflect.apply(target, thisArg, args);
},
});

markAsInstrumented(handler.errorHandler);
}

if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {
handler.scheduled = new Proxy(handler.scheduled, {
apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<Env>>) {
Expand Down
91 changes: 91 additions & 0 deletions packages/cloudflare/test/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ import * as SentryCore from '@sentry/core';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { CloudflareClient } from '../src/client';
import { withSentry } from '../src/handler';
import { markAsInstrumented } from '../src/instrument';

// Custom type for hono-like apps (cloudflare handlers) that include errorHandler and onError
type HonoLikeApp<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown> = ExportedHandler<
Env,
QueueHandlerMessage,
CfHostMetadata
> & {
onError?: () => void;
errorHandler?: (err: Error) => Response;
};

const MOCK_ENV = {
SENTRY_DSN: 'https://[email protected]/1337',
Expand Down Expand Up @@ -931,6 +942,86 @@ describe('withSentry', () => {
});
});
});

describe('hono errorHandler', () => {
test('captures errors handled by the errorHandler', async () => {
const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException');
const error = new Error('test hono error');

const honoApp = {
fetch(_request, _env, _context) {
return new Response('test');
},
onError() {}, // hono-like onError
errorHandler(err: Error) {
return new Response(`Error: ${err.message}`, { status: 500 });
},
} satisfies HonoLikeApp<typeof MOCK_ENV>;

withSentry(env => ({ dsn: env.SENTRY_DSN }), honoApp);

// simulates hono's error handling
const errorHandlerResponse = honoApp.errorHandler?.(error);

expect(captureExceptionSpy).toHaveBeenCalledTimes(1);
expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, {
mechanism: { handled: false, type: 'cloudflare' },
});
expect(errorHandlerResponse?.status).toBe(500);
});

test('preserves the original errorHandler functionality', async () => {
const originalErrorHandlerSpy = vi.fn().mockImplementation((err: Error) => {
return new Response(`Error: ${err.message}`, { status: 500 });
});

const error = new Error('test hono error');

const honoApp = {
fetch(_request, _env, _context) {
return new Response('test');
},
onError() {}, // hono-like onError
errorHandler: originalErrorHandlerSpy,
} satisfies HonoLikeApp<typeof MOCK_ENV>;

withSentry(env => ({ dsn: env.SENTRY_DSN }), honoApp);

// Call the errorHandler directly to simulate Hono's error handling
const errorHandlerResponse = honoApp.errorHandler?.(error);

expect(originalErrorHandlerSpy).toHaveBeenCalledTimes(1);
expect(originalErrorHandlerSpy).toHaveBeenLastCalledWith(error);
expect(errorHandlerResponse?.status).toBe(500);
});

test('does not instrument an already instrumented errorHandler', async () => {
const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException');
const error = new Error('test hono error');

// Create a handler with an errorHandler that's already been instrumented
const originalErrorHandler = (err: Error) => {
return new Response(`Error: ${err.message}`, { status: 500 });
};

// Mark as instrumented before wrapping
markAsInstrumented(originalErrorHandler);

const honoApp = {
fetch(_request, _env, _context) {
return new Response('test');
},
onError() {}, // hono-like onError
errorHandler: originalErrorHandler,
} satisfies HonoLikeApp<typeof MOCK_ENV>;

withSentry(env => ({ dsn: env.SENTRY_DSN }), honoApp);

// The errorHandler should not have been wrapped again
honoApp.errorHandler?.(error);
expect(captureExceptionSpy).not.toHaveBeenCalled();
});
});
});

function createMockExecutionContext(): ExecutionContext {
Expand Down