一、异常拦截器
目标:访问路径不存在时,返回结果中包含请求路径path
实现:1、创建一个异常过滤器,负责将捕获作为HttpException类实例的异常
2、访问底层平台Request、Response,通过访问Request对象,提取原始url将其包含在日志信息中
3、使用Response.jon()方法,使用Response对象直接控制发送的响应
二、实现逻辑
新建src/filter.ts
import { ArgumentsHost, ExceptionFilter, Catch, 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({
data: exception.message,
time: new Date().getTime(),
success: false,
path: request.url,
code: status
});
}
}
三、main.ts中注册异常拦截器
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { HttpFilter } from './common/filter';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule); app.useGlobalFilters(new HttpFilter());
await app.listen(3000);
}
bootstrap();