@@ -272,11 +272,23 @@ function getStatusCodeFromResponse(error: MiddlewareError): number {
272
272
return statusCode ? parseInt ( statusCode as string , 10 ) : 500 ;
273
273
}
274
274
275
+ /** Returns true if response code is internal server error */
276
+ function defaultShouldHandleError ( error : MiddlewareError ) : boolean {
277
+ const status = getStatusCodeFromResponse ( error ) ;
278
+ return status >= 500 ;
279
+ }
280
+
275
281
/**
276
282
* Express compatible error handler.
277
283
* @see Exposed as `Handlers.errorHandler`
278
284
*/
279
- export function errorHandler ( ) : (
285
+ export function errorHandler ( options ?: {
286
+ /**
287
+ * Callback method deciding whether error should be captured and sent to Sentry
288
+ * @param error Captured middleware error
289
+ */
290
+ shouldHandleError ?( error : MiddlewareError ) : boolean ;
291
+ } ) : (
280
292
error : MiddlewareError ,
281
293
req : http . IncomingMessage ,
282
294
res : http . ServerResponse ,
@@ -288,20 +300,23 @@ export function errorHandler(): (
288
300
_res : http . ServerResponse ,
289
301
next : ( error : MiddlewareError ) => void ,
290
302
) : void {
291
- const status = getStatusCodeFromResponse ( error ) ;
292
- if ( status < 500 ) {
293
- next ( error ) ;
303
+ const shouldHandleError = ( options && options . shouldHandleError ) || defaultShouldHandleError ;
304
+
305
+ if ( shouldHandleError ( error ) ) {
306
+ withScope ( scope => {
307
+ if ( _req . headers && isString ( _req . headers [ 'sentry-trace' ] ) ) {
308
+ const span = Span . fromTraceparent ( _req . headers [ 'sentry-trace' ] as string ) ;
309
+ scope . setSpan ( span ) ;
310
+ }
311
+ const eventId = captureException ( error ) ;
312
+ ( _res as any ) . sentry = eventId ;
313
+ next ( error ) ;
314
+ } ) ;
315
+
294
316
return ;
295
317
}
296
- withScope ( scope => {
297
- if ( _req . headers && isString ( _req . headers [ 'sentry-trace' ] ) ) {
298
- const span = Span . fromTraceparent ( _req . headers [ 'sentry-trace' ] as string ) ;
299
- scope . setSpan ( span ) ;
300
- }
301
- const eventId = captureException ( error ) ;
302
- ( _res as any ) . sentry = eventId ;
303
- next ( error ) ;
304
- } ) ;
318
+
319
+ next ( error ) ;
305
320
} ;
306
321
}
307
322
0 commit comments