Nest.js

5、Nest.js 中的异常处理和AOP编程

2018-07-31  本文已影响580人  RoyLin1996

为什么会出现异常?

在 UsersController 我们有如下代码:

    @Get(':id')
    async findOne(@Param() params): Promise<User> {
        
        return await this.usersService.findOne(params.id);
    }

我们希望接收一个以 Get 方式提交的用户 id 值,并且期望它永远是 number 类型的。
现在我们的程序直接将 params.id 传入了 service 层,并且期望 service 层能够帮我们找到对应的用户并返回给客户端。
在这里直接使用了客户端上传的 id,并没有对参数的类型做校验,如果 id 不是 number 类型,那么将可能会引发异常。

如何处理参数错误

如果我们对 id 进行校验,然后没有得到预期的值,那么我们该如何返回错误信息呢?

一种方法是使用 @Res 自己处理 HTTP 响应,将 findOne 改写如下:

    @Get(':id')
    async findOne(@Res() res, @Param() params): Promise<User> {

        let id = parseInt(params.id);

        if(isNaN(id) || typeof id !== 'number' || id <= 0) {
            return res.status(HttpStatus.BAD_REQUEST).send({
                errorCode: 10001,
                errorMessage: '用户编号错误'
            });
        }
        
        return res.status(HttpStatus.OK).send({
            errorCode: 0,
            errorMessage: '请求成功',
            data: await this.usersService.findOne(id)
        });
    }

这种方式的优点是非常的灵活,我们可以完全控制 HTTP 响应,但是它让代码变得非常冗余而且耦合度太高。
聪明的软件工程师就在思考如何用一种统一的方式来处理这些异常和错误。

AOP

前面说过一个复杂系统需要自顶向下的纵向划分成多个模块,但是我们发现每个模块都要处理类似上面的异常和错误,这个时候统一的异常处理层将作为一个横向的切面贯穿我们系统中的所有模块,这种编程方式,我们就称之为 面向切面编程 (Aspect Oriented Programming 简称:AOP)

Nest 内置了全局异常处理层

一旦应用程序抛出异常,Nest 便会自动捕获这些异常并给出 JSON 形式的响应。
如果访问 http://127.0.0.1:3000/member ,这将抛出一个 HTTP Exception,并得到如下输出:

{
    "statusCode":404,
    "error":"Not Found",
    "message":"Cannot GET /member"
}

如果是未知的异常类型,则会是下面这样:

{
    "statusCode": 500,
    "message": "Internal server error"
}

HttpException

Nest 内置了 HttpException 类用来处理异常,我们改写上面的例子:

    @Get(':id')
    async findOne(@Param() params): Promise<User> {

        let id = parseInt(params.id);

        if(isNaN(id) || typeof id !== 'number' || id <= 0) {

            throw new HttpException('用户编号错误', HttpStatus.BAD_REQUEST);
           
        }
        
        return await this.usersService.findOne(id);

    }

现在我们的代码精简了不少,但是有一个问题,我们自定义的错误状态码没有了,怎么办?
推荐的做法是创建自己的异常类并继承 HttpException 或它的派生类,然后使用 异常过滤器 来自定义响应格式。

Nest 帮我们内置了很多异常的模板:

使用异常过滤器实现统一错误处理横切面

首先来看如何创建一个异常过滤器,并捕获HttpException,然后设置我们自己的响应逻辑:

$ nest g f common/filters/http-exception
CREATE /src/common/filters/http-exception/http-exception.filter.ts (189 bytes)

把 http-exception/ 这一层目录去掉,修改默认生成的代码,如下:

src/common/filters/http-exception.filter.ts

import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {

  catch(exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus()

    response
      .status(status)
      .json({
        statusCode: status,
        date: new Date().toLocaleDateString(),
        path: request.url,
      });
  }

}

异常过滤器就是实现了 ExceptionFilter 接口,并且用 @Catch 装饰器修饰的类。
我们还需要修改 main.ts,在全局范围内使用我们的异常过滤器:

import { NestFactory } from '@nestjs/core';
import { AppModule } from 'app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(3000);
}
bootstrap();

现在访问 http://127.0.0.1:3000/users/exception,我们的异常过滤器起作用了:

{
  "statusCode":400,
  "date":"2018-7-31",
  "path":"/users/exception"
}

返回合适的HTTP状态码

为每一次的响应返回合适的HTTP状态码,好的响应应该使用如下的状态码:

使用身份认证(authentication)和授权(authorization)错误码时需要注意:

当用户请求错误时,提供合适的状态码可以提供额外的信息:

业务状态码

我们也想返回像微信公众平台一样的业务状态码时该怎么办?


image.png

这个时候我们需要定义自己的异常类,并用全局异常过滤器捕获它然后更改响应,首先我们需要规划好自己的业务状态码,在 common 目录中创建 enums 目录并创建 api-error-code.enum.ts:

src/common/enums/api-error-code.enum.ts

export enum ApiErrorCode {
    TIMEOUT = -1, // 系统繁忙
    SUCCESS = 0, // 成功

    USER_ID_INVALID = 10001 // 用户id无效
}

定义一个 ApiException 继承自 HttpException:

$ nest g e common/exceptions/api
CREATE /src/common/exceptions/api/api.exception.ts (193 bytes)

把 api/ 这一层目录去掉,修改默认的代码,如下:

src/common/exceptions/api.exception.ts

import { HttpException, HttpStatus } from '@nestjs/common';
import { ApiErrorCode } from '../enums/api-error-code.enum';

export class ApiException extends HttpException {

  private errorMessage: string;
  private errorCode: ApiErrorCode;

  constructor(errorMessage: string, errorCode: ApiErrorCode, statusCode: HttpStatus) {

    super(errorMessage, statusCode);

    this.errorMessage = errorMessage;
    this.errorCode = errorCode;
  }

  getErrorCode(): ApiErrorCode {
    return this.errorCode;
  }

  getErrorMessage(): string {
    return this.errorMessage;
  }
}

我们现在应该让 UsersController 中的 findOne 抛出 ApiException:

    @Get(':id')
    async findOne(@Param() params): Promise<User> {

        let id = parseInt(params.id);

        if(isNaN(id) || typeof id !== 'number' || id <= 0) {

           throw new ApiException('用户ID无效', ApiErrorCode.USER_ID_INVALID, HttpStatus.BAD_REQUEST);
          
        }
        
        return await this.usersService.findOne(id);

    }

这样还没完,我们的全局过滤器并没有加入识别ApiException的逻辑,现在修改全局过滤器的逻辑:

import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { ApiException } from '../exceptions/api.exception';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {

  catch(exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus()

    if (exception instanceof ApiException) {

      response
        .status(status)
        .json({
          errorCode: exception.getErrorCode(),
          errorMessage: exception.getErrorMessage(),
          date: new Date().toLocaleDateString(),
          path: request.url,
        });

    } else {

      response
        .status(status)
        .json({
          statusCode: status,
          date: new Date().toLocaleDateString(),
          path: request.url,
        });
    }
  }

}

再进行一次错误的访问 http://127.0.0.1:3000/users/exception, 得到下面的响应:

{
  "errorCode":10001,
  "errorMessage":"用户ID无效",
  "date":"2018-7-31",
  "path":"/users/exception"
}

看起来不错,我们不仅有正确的 HTTP 响应码还有了自定义的业务状态码!
更好的处理方式是创建 UsersException 继承自 ApiException。

上一篇:4、Nest.js 中的模块化设计
下一篇:6、Nest.js 中的管道与验证器

上一篇下一篇

猜你喜欢

热点阅读