自定义一个的异常拦截器需要实现 ExceptionFilter 类
先看全部代码 👇:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import { ArgumentsHost, Catch, ExceptionFilter, HttpException, } from '@nestjs/common'; import { Request, Response } from 'express';
@Catch(HttpException) export class HttpFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const request = ctx.getRequest<Request>(); const response = ctx.getResponse<Response>(); const status = exception.getStatus();
response.status(status).json({ success: false, time: new Date(), data: exception.message, status, path: request.path, message: '请求失败辣', }); } }
|
@Catch() 装饰器指明需要捕获的异常
这里指明捕获 HttpException 即只捕获http异常。
实现ExceptionFilter类中的catch方法
catch方法有两个参数:
exception: 绑定的异常类型
host: 根据执行上下文获取处理程序参数ArgumentsHost
host.switchToHttp() 选择执行上下文
在执行上下文中,可以获取到请求与响应。不过要方便后续的使用还是建议添加类型断言
从express中取出类型
1 2 3 4 5 6 7
| import { Request, Response } from 'express'; ...
const ctx = host.switchToHttp(); const request = ctx.getRequest<Request>(); const response = ctx.getResponse<Response>();
|
当前请求状态
当前的请求状态就是从第一个参数exception异常中去获取。
最后需要将拦截的请求重新发送给客户端
封装自定义的拦截响晴信息
1 2 3 4 5 6 7 8 9
| response.status(status).json({ success: false, time: new Date(), data: exception.message, status, path: request.path, message: '请求失败辣', });
|
添加拦截
添加全局拦截
使用 useGlobalFilters 添加全局拦截
1 2 3 4 5 6 7 8
|
async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalFilters(new HttpFilter()); await app.listen(3000); }
|
指定拦截
使用@UseFilters指定函数拦截或类拦截
1 2 3 4 5 6 7 8 9 10 11
| @Controller() export class AppController { constructor(private readonly appService: AppService) {}
@Get('/error') @UseFilters(HttpFilter2) getError(): string { return this.appService.getError(); } }
|