8000 feat(node): Add shouldHandleError option to fastify error handler · benjick/sentry-javascript@0459800 · GitHub
[go: up one dir, main page]

8000
Skip to content

Commit 0459800

Browse files
committed
feat(node): Add shouldHandleError option to fastify error handler
1 parent 5f3f531 commit 0459800

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

packages/node/src/integrations/tracing/fastify.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,27 @@ const _fastifyIntegration = (() => {
6161
*/
6262
export const fastifyIntegration = defineIntegration(_fastifyIntegration);
6363

64+
interface FastifyHandlerOptions {
65+
/**
66+
* Callback method deciding whether error should be captured and sent to Sentry
67+
* @param error Captured middleware error
68+
*/
69+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
70+
shouldHandleError?(this: void, request: any, reply: any, error: Error): boolean;
71+
}
72+
6473
/**
6574
* Setup an error handler for Fastify.
6675
*/
67-
export function setupFastifyErrorHandler(fastify: Fastify): void {
76+
export function setupFastifyErrorHandler(fastify: Fastify, options?: FastifyHandlerOptions): void {
6877
const plugin = Object.assign(
6978
function (fastify: Fastify, _options: unknown, done: () => void): void {
70-
fastify.addHook('onError', async (_request, _reply, error) => {
71-
captureException(error);
79+
const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError;
80+
81+
fastify.addHook('onError', async (request, reply, error) => {
82+
if (shouldHandleError(request, reply, error)) {
83+
captureException(error, { mechanism: { type: 'middleware', handled: false } });
84+
}
7285
});
7386

7487
// registering `onRequest` hook here instead of using Otel `onRequest` callback b/c `onRequest` hook
@@ -131,3 +144,10 @@ function addFastifySpanAttributes(span: Span): void {
131144
span.updateName(name.replace(/^fastify -> /, ''));
132145
}
133146
}
147+
148+
/** Returns true if response code is internal server error */
149+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
150+
function defaultShouldHandleError(_request: any, reply: any, _error: Error): boolean {
151+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
152+
return reply.statusCode >= 500;
153+
}

0 commit comments

Comments
 (0)
0