如何将所有异常记录到nest.js中的自定义记录器



我有一个自定义日志记录服务,该服务以可以运送到第三方日志收集服务的方式输出结构性日志。

我想知道什么是确保我捕获所有错误的最佳方法,从http错误到未经处理的JS错误(例如TypeErrors,未被拒绝的拒绝诺言等(,并将其运送到Logger。

我看到的大多数示例仅http错误。

您可能可以在这里查看不发育的感受,但与Nestjs

无关

https://nodejs.org/docs/latest/api/process.html#process_event_event_uncaughtexception

但是要小心,因为您可以破坏应用程序的稳定性

编辑

您可以利用全局过滤器,如下所示,https://docs.nestjs.com/exception-filters

App.useGlobalFilters(new MyFilter())

,如果您想使用DI,可以使用令牌

将其添加到提供商集合中的AppModule中
Provide: APP_FILTER,
useClass: MyFilter

为了记录目的,您可以尝试连接全局拦截器:

app.useGlobalInterceptors(new YourInterceptor());

在我的情况下,我使用了内置的Nestjs-Pino Logger Interceptor:

import { Logger, LoggerErrorInterceptor } from 'nestjs-pino';
// bootstrap function
// const app = ...
const logger = app.get(Logger);
app.useLogger(logger);
app.useGlobalInterceptors(new LoggerErrorInterceptor());
// ...rest

这是一个示例,捕获所有异常,进行日志记录,而无需修改实际响应。

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { MyLogger } from '../modules/logger/logger.service';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
  catch(exception: unknown, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    const logger = new MyLogger();
    logger.setContext(exception['name']);
    logger.error(exception['message']);
    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    httpAdapter.reply(ctx.getResponse(), exception['response'], httpStatus);
  }
}

然后,在main.ts中:

app.useGlobalFilters(new AllExceptionsFilter(app.get(HttpAdapterHost)));

最新更新