【问题标题】:Integrate nestjs with sentry将nestjs与哨兵集成
【发布时间】:2020-02-02 23:12:44
【问题描述】:

我想将 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 + "\n");
});

app.listen(3000);

【问题讨论】:

  • 你的问题不是很清楚,但是对于你提供的代码,除了没有和nest.js集成之外,还有其他问题吗?
  • 一切都很好,只是这部分代码是问题 app.get('/', function rootHandler(req, res) { res.end('Hello world!'); });

标签: javascript nestjs


【解决方案1】:

为了将哨兵与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.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,您可以在此处进行示例。

【讨论】:

    【解决方案2】:

    我刚刚在 Github 上创建了一个示例项目来回答这个问题:

    https://github.com/ericjeker/nestjs-sentry-example

    以下是 README 文件的部分副本。如果您有任何问题,请告诉我。

    创建需要的元素

    创建 Sentry 模块、服务和拦截器

    $ nest g module sentry
    $ nest g service sentry
    $ nest g interceptor sentry/sentry
    

    哨兵模块

    创建SentryModule.forRoot() 方法并在其中添加Sentry.init(options)

    AppModule 中调用SentryModule.forRoot({...}) 并与您的首选配置集成(我使用ConfigModule.env 文件)。

    AppModule.configure()中添加对Express requestHandler中间件的调用。

      configure(consumer: MiddlewareConsumer): void {
        consumer.apply(Sentry.Handlers.requestHandler()).forRoutes({
          path: '*',
          method: RequestMethod.ALL,
        });
      }
    

    使用该中间件很重要,否则当前 Hub 将是全局的,并且 当 Sentry 通过线程创建 Hub 并且 Node.js 不是多线程时,您会遇到冲突。

    哨兵服务

    我们要在服务的构造函数中初始化事务。你可以 在那里自定义您的主要交易。

    请注意,因为我注入了 Express 请求,所以服务必须是请求范围的。你 可以阅读更多关于here的信息。

    @Injectable({ scope: Scope.REQUEST })
    export class SentryService {
      constructor(@Inject(REQUEST) private request: Request) {
        // ... etc ...
      }
    }
    

    哨兵拦截器

    SentryInterceptor 将捕获异常并完成事务。还请 请注意,当我们注入 SentryService 时,它必须是请求范围内的:

    @Injectable({ scope: Scope.REQUEST })
    export class SentryInterceptor implements NestInterceptor {
      constructor(private sentryService: SentryService) {}
    
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // ... etc ...
      }
    }
    

    例如,我添加了一个跨度。这不是必需的,但它只会使 Sentry 的性能查看器中的跟踪更好。

    您只需注入SentryService 并调用startChild 或调用当前span 的startChild 方法即可在应用程序的任何位置添加更多span。

    【讨论】:

    • 这是一个令人难以置信的答案。这就是使用 Nest 8 的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2019-11-10
    • 2020-03-15
    • 2014-05-17
    相关资源
    最近更新 更多