javascript - 全局错误过滤器不捕获来自服务的异常,只捕获 Controller

标签 javascript exception nestjs

我有一个 NestJS API,我在其中实现了一个错误过滤器来捕获各种异常。在 main.ts 中,我将 api 设置为在全局范围内使用过滤器。

显然,它只捕获 Controller 中的错误,因为当我在服务上下文中抛出异常时,异常在控制台中抛出并且 api 失败。

main.ts:

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './exception-filters/http-exception.filter';
import { AllExceptionsFilter } from './exception-filters/exception.filter';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter());

  const options = new DocumentBuilder()
    .setTitle('API Agendamento.Vip')
    // .setDescription('')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);
  // app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new AllExceptionsFilter());
  await app.listen(process.env.PORT || 3001);
}
bootstrap();

在服务方法中抛出这些异常

  if (err) { throw new InternalServerErrorException('error', err); }

  if (!user) { throw new NotFoundException('device info missing'); }

  if (!user.active) { throw new HttpException('active error', 400); }

我的异常过滤器:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, BadRequestException } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response: FastifyReply<any> = ctx.getResponse();
    const request: FastifyRequest = ctx.getRequest();

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

    const objResponse = Object.assign(exception, {
      timestamp: new Date().toISOString(),
      path: request.req.url
    });

    response.status(status).send({
      objResponse
    });
  }
}

Node 控制台抛出异常,导致 api 停止。

只有在 Controller 的上下文中,它们才会被过滤器捕获。

我该怎么做才能在服务中捕获异常?

最佳答案

看到你的过滤器后,我们可以尝试两件事,首先将 HttpException 添加到 @Catch 装饰器(只是为了测试,我相信不会有任何区别)

@catch(HttpException)
export class AllExceptionFilter implements ExceptionFilter {
  /*your code*/
}

然后不使用 app.useGlobalFilters,而是在应用程序模块中添加以下内容:

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { AllExceptionsFilter } from './exception-filters/exception.filter';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: AllExceptionFilter,
    },
  ],
})
export class AppModule {}

这会将过滤器置于全局范围内,并使您能够使用全局注入(inject)器,这是我一直用于全局(过滤器、防护、管道)的方法,对我来说就像一个魅力

关于javascript - 全局错误过滤器不捕获来自服务的异常,只捕获 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138847/

相关文章:

java - 重新启动 JSR352 作业时出现反序列化检查点信息的问题 - ClassNotFoundException : [B

java - 线程中出现异常 "Thread-3"java.lang.NoSuchMethodError : org. apache.http.impl.client.DefaultRedirectStrategy.<init>([Ljava/lang/String;)V

node.js - 从jeft连接查询TypeORM中选择特定的列

Javascript对数组进行两次排序

javascript - 如何防止幻灯片循环回到开头?

c++ - 嵌入式系统中的错误处理

mongodb - NestJS - 使用 mongoose 通过枚举嵌入嵌套文档

NestJS:如何在@Query 对象中转换数组

javascript - 只有一次ajax调用,等到下一次点击成功

javascript - 可以在移动设备(iOS/Android)上在后台观看位置吗?