Nest
异常过滤器 filter
异常捕获与统一响应内容
说明
当程序发生任何异常时都会进入异常过滤器的捕获内,并且生成可读性友好的返回内容;
如果发生的异常不是继承 HttpException或者是其本身及子类的话,则会抛出通用异常内容;
{
"statusCode": 500,
"message": "Internal server error"
}抛出异常
import { Injectable, HttpException, HttpStatus, BadRequestException } from '@nestjs/common';
@Injectable()
export class UsersService {
create(createUserDto: CreateUserDto) {
if (!user.phone === db.user.phone) {
throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST);
// 也可以传递对象抛出错误
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: '用户已存在'
}, HttpStatus.BAD_REQUEST);
// 也可以使用子类抛出更详细的异常
/**
* {
* "message": "未知的错误",
* "error": "unknown error",
* "statusCode": 400
* }
*/
throw new BadRequestException('用户已存在', {
cause: new Error(),
description: 'User already exists'
})
}
return createUserDto;
}
}在 Nest 中内置的异常有很多,由于 HttpStatus 的存在在未知的情况下没有必要抛出准确的异常,可以完全使用 HttpException + HttpStatus 抛出对应的异常即可。
错误的信息,默认情况下不会被日志记录,如果确实有这个需求可以使用自定义异常解决这个问题;
同时在大多数的场景下,无论是否存在错误,接口的返回总是希望能够保持统一的返回结构,自定义异常也可以做错误信息的 format。
自定义异常
自定义异常必须实现 ExceptionFilter<T> 类,指定的方法为 catch(exception: T, host: ArgumentHost)
import { Catch, ExcetionFilter, ArgumentHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
// 告知 nest 只查找 http 的异常,也可以通过 , 分割为多种异常定义过滤器
@Catch(HttpException)
export class HttpExceptionFilter implements ExcetionFilter {
catch(exception: unknown, host: ArgumentHost) {
// 返回一个适用于 http 上下文的对象
const ctx = host.switchToHttp();
const req = ctx.getRequest<Request>();
const res = ctx.getResponse<Response>();
const statusCode = exception.getStatus();
// 所有的 http 异常都会统一返回着三个字段
res.status(statusCode).json({
statusCode,
timestamp: new Date().toISOString(),
path: req.path,
});
}
}ArgumentHost
这是一个非常重要的上下文对象,在 守卫、过滤器、拦截器 中都会碰到,由于该框架支持 HTTP、RPC、WebSocket,所以提供了这个对象用于在特殊的地方辨别当前的程序类型。
// 获取当前程序类型
host.getType(); // http | rpc | ws
// 切换对应的上下文
/**
* ctx.getRequest();
* ctx.getResponse();
* ctx.getNext();
*/
host.switchToHttp();
/**
* ctx.getData<T>():
* ctx.getContext<T>(): T;
*/
host.switchToRpc();
/**
* ctx.getData<T>(): T;
* ctx.getClient<T>(): T;
*/
host.switchToWs();捕获所有异常
捕获所有异常将 @Catch 不传递参数即可;
另外可以使用 HttpAdapterHost 适配器来抹平平台的差异,不用考虑 express or fastify 框架。该对象来自 @nestjs/core
import {
Catch,
ExceptionFilter,
ArgumentsHost,
HttpException,
HttpStatus
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
@Catch()
export class CatchEverythingFilter implements ExceptionFilter {
// 注入适配器
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost) {
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
// 判定状态码
const httpStatus = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const resBody = {
statusCode: httpStatus,
timestamp: new Date().toISOString(),
// 从 request 的上下文中获取 url
path: httpAdapter.getRequestUrl(ctx.getRequest())
}
// 发送响应信息(内部抹平平台差异)
httpAdapter.reply(ctx.getResponse(), resBody, httpStatus);
}
}http 适配器
抹平依赖框架的差异,可以从跟实例中获取,也可以是一个可以注入的对象;该对象来自于 @nestjs/core 中。
const app = await NestFactory.create(AppModule);
const httpAdapter = app.getHttpAdapter();
export class UsersService {
constructor(private adapterHost: HttpAdapterHost) {}
}值得注意的是这个 HttpAdapterHost 并不是真正的实例,要通过解构获取 httpAdapter;
const { httpAdapter } = this.adapterHost;
// 获取 request url
httpAdapter.getRequestUrl(ctx.getRequest());
// 获取 request 方式
httpAdapter.getRequestMethod(ctx.getRequest());
// 获取请求的 hostName
httpAdapter.getRequestHostname(ctx.getRequest());
// 设置返回的响应头
httpAdapter.appendHeader(ctx.getResponse(), 'custom-header', 'custom-value');
// 获取框架类型
httpAdapter.getType() // express
// 返回内容
httpAdapter.reply(ctx.getResponse(), resBody, httpStatus);其实还有很多内容,可以使用鼠标点入看下上面的所有方法。