将nestjs与哨兵相结合

2022-03-04 00:00:00 javascript nestjs

我想将Sentry与nest.js+express集成,但我刚刚找到了Raven版本,但该版本已被弃用。 我遵循与Express集成的哨兵文档,但不知道如何处理‘所有控制员都应该住在这里’这一部分。

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 + "
");
});

app.listen(3000);

解决方案

要将哨兵与Nestjs集成,我们需要执行以下步骤:

  1. 安装NPM I Nest-Raven
  2. 在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. 用于app.module e.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() },
      ],
    }),
  }],
})

此处https://github.com/getsentry/sentry-javascript/issues/2269跟踪问题,您可以按照示例操作。

相关文章