likes
comments
collection
share

初尝nestjs,捕获异常(第二章)

作者站长头像
站长
· 阅读数 3

背景

我们在开发接口的过程中可能会存在很多错误需要处理,如果我们每一个错误都需要单独去处理的话,可能重复性的工作就比较大,降低了效率;这个时候我们就需要同意去做处理,然后我们在抛出错误的时候只需要携带返回错误信息就ok了,这样就大大的增加了我们开发效率以及统一管理。

未处理异常报错

示例:模拟报错

我们通过JSON.parse方式去解析data(data没有传值,或者是一个数值字符串一类的),这个时候正常报错应该是:Unexpected token o in JSON at position 1

但是实际返回的报错是:internet server error 看以下

@Post('v2')
  getHello(@Body() data: any): string {
    JSON.parse(data);
     return this.AuthService.getHello(data);s
  }

报错信息:

{
    "code": 500,
    "msg": "internet server error"
}

我们从以上可以看出:服务器返回的信息是指-->服务器错误,没有返回特定的一些信息,那么我们在排查错误的时候可能就会存在一定的难度,所以有统一的异常返回错误可以,尽快的查到原因以及给前端调用时给与对应的提示。

异常错误统一处理

filter/allException.filter.ts

新建统一处理文件,通过@Catch()进行捕获错误,然后根据相关的api去获取传递的参数,并做出相对应的处理,即可。这儿需要注意两个点:

  • Logger是在控制台打印相关的错误信息
  • response.status(responseStatus)是返回对应的状态以及信息

具体的东西大家可以根据自己的需要进行修改并看相关的文档 统一异常处理相关文档,我目前写的这个也只是简单的示例,仅供参考。

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  Logger,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';

// 捕获所有异常
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const responseStatus =
      exception instanceof HttpException
        ? 200
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const message =
      exception instanceof HttpException
        ? exception.message
        : 'internet server error';

    new Logger('HttpExceptionFilter').error(
      request.url,
      exception.message,
      exception.stack,
    );
    
    response.status(responseStatus).json({
      code: status,
      msg: message,
    });
  }
}

main.ts

在其文件中引入

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from "./filter/allException.filter";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new AllExceptionsFilter()); // 在这儿呢
  await app.listen(3000);
}
bootstrap();

模拟抛出错误

最后我们就是进行测试了,看看异常抛出错误是什么? throw new HttpException(error, HttpStatus.BAD_REQUEST)该串代码是抛出了错误以及状态。

示例:

import { Body, Post, HttpException, HttpStatus } from '@nestjs/common';
@Post('v2')
  getHello(@Body() data: any): string {
    try {
      JSON.parse(data);
      return this.AuthService.getHello(data);
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }

抛出错误:

我们现在可以看到返回的错误就是JSON.parse解析失败时返回的错误信息了,说明我们这个抛出异常是没得问题的了。

{
    "code": 400,
    "msg": "Unexpected token o in JSON at position 1"
}

做到这儿了,我们异常统一处理基本上就完成了,如果有兴趣的朋友可以去试试吧!