Search code examples
node.jsexpresssentry

How to log 4xx errors into sentry?


At the moment, server errors with statuses 5xx are logged in sentry.
How can I make errors with the 4xx status be logged as warnings?
Init sentry:

Sentry.init({
  dsn: 'https://server.com/8',
  integrations: [
    new Sentry.Integrations.Http({ tracing: true }),
    new Tracing.Integrations.Express({ app: server }),
    new Tracing.Integrations.Postgres(),
    new ExtraErrorDataIntegration(),
  ],
  environment: 'ENV',
  release: 'n/a',
  tracesSampleRate: 1.0,
  enabled: true,
});

Solution

  • shouldHandleError intercepts the data.
    In this handler, you can change the level

    server.use(Sentry.Handlers.errorHandler({
      shouldHandleError(error) {
        if (/^[4]/.test(error.statusCode)) {
          Sentry.configureScope((scope) => {
            scope.setLevel(Sentry.Severity.Warning);
          });
        }
        return true;
      },
    }));