@@ -272,11 +272,23 @@ function getStatusCodeFromResponse(error: MiddlewareError): number {
272272 return statusCode ? parseInt ( statusCode as string , 10 ) : 500 ;
273273}
274274
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+
275281/**
276282 * Express compatible error handler.
277283 * @see Exposed as `Handlers.errorHandler`
278284 */
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+ } ) : (
280292 error : MiddlewareError ,
281293 req : http . IncomingMessage ,
282294 res : http . ServerResponse ,
@@ -288,20 +300,23 @@ export function errorHandler(): (
288300 _res : http . ServerResponse ,
289301 next : ( error : MiddlewareError ) => void ,
290302 ) : 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+
294316 return ;
295317 }
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 ) ;
305320 } ;
306321}
307322
0 commit comments