简体   繁体   中英

How to send 4XX and 5XX errors to sentry?

I want to capture any 4XX and 5XX errors in sentry. I found out that sentry by default does not log 4XX errors into sentry, so I've added the shouldHandleError error handler as well, but the 5XX/4XX responses are still not going to sentry.


import express, { Express } from 'express';
import * as Sentry from '@sentry/node';
import config from '../../../config/default';
import mountRoutes from './routers';

initSentry();
const app = express();
setupSentryHeaders(app);
app.use(express.json());

app.get('/',(req: any , res: any) => {
  res.sendStatus(502)
})
setSentryErrorHandler(app);

app.listen(8000, async () => {
  console.log(`service running...`);
});

function initSentry() {
  Sentry.init({
    dsn: config.sentry_dsn,
    environment: "development",
    attachStacktrace: true
  });
}

function setSentryErrorHandler(app: Express) {
  app.use(Sentry.Handlers.errorHandler({
    shouldHandleError(error) {
      const statusCode = error.statusCode
      if(statusCode > 400 ){
        return true;
      }
      return false;
    },
  }));
}
function setupSentryHeaders(app: Express) {
  app.use(Sentry.Handlers.requestHandler() as express.RequestHandler);
}

You are confusing errors with proper responses.

res.status(502) is a valid response, which will end the middleware pipeline and none of error middleware will be triggered, as the response is request is already complete.

What you are looking for, are errors, that assigned status code was 502 in this case, and then handled accordingly.

app.get('/',(_, res) => {
  const err = new Error('Something went wrong');
  err.statusCode = 502;
  throw err;
})

This + your shouldHandleError will make it "catcheable", as default error handler of express, assigns response status code from err.statusCode , see "The default error handler" of https://expressjs.com/en/guide/error-handling.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM