返回文章列表 →

Note

异常

nestjs的异常介绍

发布于 更新于

异常

HttpException

Nest 提供了一个内置的类,一套标准的异常。从 @nestjs/common 包中导入。HttpException 构造函数最少需接收两个必选参数来决定响应内容:

  • response
    该参数定义了 JSON 响应体。response 可以是 string 或 object ,若仅覆盖 JSON 响应体中的消息部分,传入 string 即可,若要覆盖整个 JSON 响应体,则在 response 参数中传入对象。JSON 响应体包含两个属性:
    • statusCode
      默认为 status 参数中提供的 HTTP状态码
    • message
      基于 status 的 HTTP 错误简短描述
  • status
    该参数定义了 HTTP状态码
  • options
    可选参数,可用于提供错误原因。该 cause 对象不会被序列化到响应对象中,但对日志记录很有帮助,能提供引发 HttpException 的内部错误的有价值信息。

例子

  1. response 为 string
@Get()
async findAll() {
 throw new HttpException('Forbidden', 403);
}

// 客户端调用此端点,响应如下
{
  "statusCode": 403,
  "message": "Forbidden"
}
  1. response 为 object 。 status 使用 HttpStatus 中的枚举,第三个可选参数增加 cause
@Get()
async findAll() {
 try {
   await this.service.findAll()
 } catch (error) {
   throw new HttpException({
     status: HttpStatus.FORBIDDEN,
     error: 'This is a custom message',
   }, HttpStatus.FORBIDDEN, {
     cause: error
   });
 }
}

// 客户端调用此端点,响应如下
{
  "status": 403,
  "error": "This is a custom message"
}

一般根据不同的业务场景抛不同的异常,不会都统一抛 HttpException ,因为HttpException 异常包含所有 NestJS HTTP 异常,包括 400xx、500xx。
如:账号已存在 throw new ConflictException('该账号已被注册') ,前端传递的参数不符 throw new BadRequestException()

NestJS异常类型即默认HTTP状态

4xx 客户端异常

HTTP NestJS 异常类 典型场景
400 BadRequestException 参数缺失、格式错误、DTO 校验失败
401 UnauthorizedException 未登录、Token 缺失或无效
403 ForbiddenException 已登录,但没有操作权限
404 NotFoundException 用户、记录或接口不存在
405 MethodNotAllowedException 请求方法不允许,如只能 POST 却发送 GET
406 NotAcceptableException 无法返回客户端 Accept 要求的内容格式
408 RequestTimeoutException 请求处理或等待超时
409 ConflictException 邮箱重复、用户名已存在、资源状态冲突
410 GoneException 资源曾经存在,但已永久删除
412 PreconditionFailedException If-Match 等请求前置条件失败
413 PayloadTooLargeException 上传文件或请求体过大
415 UnsupportedMediaTypeException 不支持请求的 Content-Type
418 ImATeapotException “I’m a teapot”,通常只用于测试或趣味场景
421 MisdirectedException 请求被发送到无法正确处理它的服务器
422 UnprocessableEntityException 格式合法,但业务语义无法处理

5xx 服务端异常

HTTP NestJS 异常类 典型场景
500 InternalServerErrorException 未知代码异常、服务器内部错误
501 NotImplementedException 接口或功能尚未实现
502 BadGatewayException 上游服务返回无效响应
503 ServiceUnavailableException 服务维护、过载或暂时不可用
504 GatewayTimeoutException 调用上游服务超时
505 HttpVersionNotSupportedException 不支持请求使用的 HTTP 版本

常见业务码

情况 HTTP 状态 业务码示例
注册成功 201 或 200 SUCCESS
缺少参数 400 VALIDATION_ERROR
未登录 401 UNAUTHORIZED
无权限 403 FORBIDDEN
用户不存在 404 USER_NOT_FOUND
邮箱已注册 409 EMAIL_ALREADY_EXISTS
服务器异常 500 INTERNAL_ERROR