全局异常过滤器未捕获某些错误

发布于 2025-01-10 06:00:03 字数 1350 浏览 0 评论 0原文

我最近创建了一个全局异常过滤器,但我刚刚注意到,它没有捕获一些错误,例如:

TypeError: Cannot read properties of undefined (reading 'dataNumber')

我的过滤器:


@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
  constructor(
    private readonly httpAdapterHost: HttpAdapterHost,
    private readonly logger: LoggerService,
  ) {}

  catch(exception: Error, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      statusCode: httpStatus,
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
      cause: `${exception.name}: ${exception.message}`,
      timestamp: new Date().toISOString(),
    };

    this.logger.error(responseBody?.cause);

    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
  }

我将它用作我的 App.module

    {
      provide: APP_FILTER,
      useClass: GlobalExceptionsFilter,
    },

目前,我还有一个 SCPModule 正在同一个 App.module 上导入,该错误发生在 SCPModule 内的 SCPService 上...每个模块都这样吗?需要使用我的过滤器作为提供者?

I've recently created a Global exception filter, but I just noticed that, some errors are not being caught by it, like:

TypeError: Cannot read properties of undefined (reading 'dataNumber')

My filter:


@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
  constructor(
    private readonly httpAdapterHost: HttpAdapterHost,
    private readonly logger: LoggerService,
  ) {}

  catch(exception: Error, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      statusCode: httpStatus,
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
      cause: `${exception.name}: ${exception.message}`,
      timestamp: new Date().toISOString(),
    };

    this.logger.error(responseBody?.cause);

    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
  }

And I'm using it as a provider on my App.module:

    {
      provide: APP_FILTER,
      useClass: GlobalExceptionsFilter,
    },

Currently, I also have a SCPModule which is being imported on the same App.module, that error is happening on the SCPService inside the SCPModule... Does every module needs to use my filter as a provider?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文