【问题标题】:Global error filter catches no exceptions from services, only controllers全局错误过滤器不捕获来自服务的异常,只捕获控制器
【发布时间】:2019-10-01 22:23:20
【问题描述】:

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

显然,它只捕获控制器中的错误,因为当我在服务上下文中抛出异常时,控制台中抛出异常并且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 停止。

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

如何才能让服务中也捕获异常?

【问题讨论】:

  • 你能展示你的异常过滤器吗?
  • @RalphJS,我编辑并包含异常过滤器
  • 您使用的三个异常是HttpExceptions,即使在catch装饰器上添加也不起作用?您也可以尝试使用APP_FILTER将过滤器添加到全局范围我将添加一个示例

标签: javascript exception nestjs


【解决方案1】:

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

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

然后在 app 模块中添加以下内容,而不是使用 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 {}

这会将过滤器置于全局范围内,并使您能够使用全局注入器,这是我一直用于 Globals(Filters, Guards, Pipes) 的方法,并且像魅力一样为我工作

【讨论】:

  • 智能不起作用。服务抛出异常时,服务不断在节点控制台上抛出异常
【解决方案2】:

问题是我从模型方法中抛出异常:

  async signInApp(dataLogin: DataLoginDto) {
        return new Promise((resolve, _reject) => {
            this.userModel.findOne({
                email: dataLogin.email
            }, (err, user) => {

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

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

// ...Code omitted

我通过在 mongoose 方法范围之外放置异常来更改代码:

 async signInApp(dataLogin: DataLoginDto) {
        const user = await this.userModel.findOne({
            email: dataLogin.email
        }).select('password active').exec();

        if (!user) { throw new NotFoundException('user not found'); }

        if (!user.active) { throw new UnauthorizedException('unable to access your account'); }

// ...Code omitted

【讨论】:

  • 有了这个你将无法控制内部服务器错误我有几乎相同的方法但是在快递上它就像一个魅力,可能是 Nestjs 的记录器和 fastify 的一些行为
  • 即使我将 MongoError 添加到 @Catch() 中?
猜你喜欢
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多