javascriptnestjs

Integrate nestjs with sentry


I want to integrate sentry with nest.js + express but I just found raven version but that is deprecated. I follow the sentry docs for integrate with express but dont know how to handle the 'All controllers should live here' part.

const express = require('express');
const app = express();
const Sentry = require('@sentry/node');

Sentry.init({ dsn: 'https://5265e36cb9104baf9b3109bb5da9423e@sentry.io/1768434' });

// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());

**// All controllers should live here
app.get('/', function rootHandler(req, res) {
  res.end('Hello world!');
});**

// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());

// Optional fallthrough error handler
app.use(function onError(err, req, res, next) {
  // The error id is attached to `res.sentry` to be returned
  // and optionally displayed to the user for support.
  res.statusCode = 500;
  res.end(res.sentry + "\n");
});

app.listen(3000);

Solution

  • For integrate sentry with nestjs we to follow this steps:

    1. install npm i nest-raven
    2. In main.ts
    async function bootstrap() {
      Sentry.init({ dsn: 'https://5265e36cb9104baf9b3109bb5da9423e@sentry.io/1768434' });
      const app = await NestFactory.create(AppModule);
      // middlewares
      await app.listen(3000);
    }
    
    1. For use it to all controllers in app.module.ts
    @Module({
      imports: [
        RavenModule,...
      ],
      controllers: [],
      providers: [{
        provide: APP_INTERCEPTOR,
        useValue: new RavenInterceptor({
          filters: [
            // Filter exceptions of type HttpException. Ignore those that
            // have status code of less than 500
            { type: HttpException, filter: (exception: HttpException) => 500 > exception.getStatus() },
          ],
        }),
      }],
    })
    

    The issue was tracking here https://github.com/getsentry/sentry-javascript/issues/2269, there you can follow an example.