@@ -61,14 +61,27 @@ const _fastifyIntegration = (() => {
61
61
*/
62
62
export const fastifyIntegration = defineIntegration ( _fastifyIntegration ) ;
63
63
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
+
64
73
/**
65
74
* Setup an error handler for Fastify.
66
75
*/
67
- export function setupFastifyErrorHandler ( fastify : Fastify ) : void {
76
+ export function setupFastifyErrorHandler ( fastify : Fastify , options ?: FastifyHandlerOptions ) : void {
68
77
const plugin = Object . assign (
69
78
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
+ }
72
85
} ) ;
73
86
74
87
// registering `onRequest` hook here instead of using Otel `onRequest` callback b/c `onRequest` hook
@@ -131,3 +144,10 @@ function addFastifySpanAttributes(span: Span): void {
131
144
span . updateName ( name . replace ( / ^ f a s t i f y - > / , '' ) ) ;
132
145
}
133
146
}
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