我想将sentry与nest.js + express集成,但我刚刚找到了raven版本,但它已被弃用。 我按照哨兵文档与 Express 集成,但不知道如何处理“所有控制器都应该住在这里”部分。
const express = require('express');
const app = express();
const Sentry = require('@sentry/node');
Sentry.init({ dsn: 'https://[email protected]/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);
已弃用:随着 Sentry 发展其 SDK(自 v8 起)并现在提供 Nest.js 文档,我的答案现已弃用。您仍然可以检查下面的存储库以获取完整的示例,或者如果您使用版本< v8.
我刚刚在 Github 上创建了一个示例项目来回答这个问题:
https://github.com/ericjeker/nestjs-sentry-example
以下是自述文件的部分副本。如果您有任何疑问,请告诉我。
创建Sentry模块、服务和拦截器
$ nest g module sentry
$ nest g service sentry
$ nest g interceptor sentry/sentry
创建
SentryModule.forRoot()
方法并在其中添加 Sentry.init(options)
。
在
SentryModule.forRoot({...})
中调用 AppModule
并与您首选的配置集成(我使用 ConfigModule
和 .env
文件)。
在
AppModule.configure()
中添加对 Express requestHandler 中间件的调用。
configure(consumer: MiddlewareConsumer): void {
consumer.apply(Sentry.Handlers.requestHandler()).forRoutes({
path: '*',
method: RequestMethod.ALL,
});
}
使用该中间件非常重要,否则当前的集线器将是全局的并且 你会遇到冲突,因为 Sentry 通过线程创建 Hub,而 Node.js 不是多线程的。
我们想要在服务的构造函数中初始化事务。你可以 在那里自定义您的主要交易。
请注意,因为我注入了 Express 请求,所以服务必须处于请求范围内。你 可以在这里阅读更多相关信息。
@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
或简单地调用当前跨度的 startChild
方法即可。
要将哨兵与nestjs集成,我们按照以下步骤操作:
async function bootstrap() {
Sentry.init({ dsn: 'https://[email protected]/1768434' });
const app = await NestFactory.create(AppModule);
// middlewares
await app.listen(3000);
}
@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,你可以按照一个例子。