过滤器
作用
主要用于捕获异常,一般用于全局
默认
bash
{
"statusCode": 500,
"message": "Internal server error"
}
过滤器使用
创建一个过滤器
ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from "@nestjs/common";
import { Request, Response } from "express";
@Catch(HttpException)
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
// 状态码
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException ? exception.message : exception.stack;
response.status(status).json({
code: status,
timestamp: new Date().toLocaleString(),
path: request.url,
message: message,
});
response.status(status).json();
}
}
挂载到全局
app.modules.ts 中 找到
providers 里面改变 providers 对应的就是名字
useClass 对应的就是你要改变的那个类名
ts
import { Module } from "@nestjs/common";
import { LoginModule } from "./Login/login.module";
// 过滤器
import { GlobalExceptionFilter } from "./Global/filter/global.filter";
import { APP_FILTER } from "@nestjs/core";
@Module({
imports: [LoginModule],
controllers: [],
providers: [
{
provide: APP_FILTER,
useClass: GlobalExceptionFilter,
},
],
})
export class AppModule {}
挂载到单个
- 找到你要找到的路由文件,直接挂载
ts
import {
Body,
Controller,
Delete,
Get,
HttpException,
Inject,
Param,
Patch,
Post,
UseFilters,
} from "@nestjs/common";
import { LoginService } from "../service/login.service";
import { CustomExceptionFilter } from "../../Global/filter/customfilter";
@Controller("logins")
export class LoginController {
@Inject()
private loginService: LoginService;
constructor() {}
@Get()
findAll() {
return this.loginService.findAll();
}
@Get("test")
@UseFilters(CustomExceptionFilter)
findAlltest() {
throw new HttpException("内部错误", 402);
}
}
注意
注意
- 这样每次抛出异常出来,会自动给你转化成 json 格式
- 要是绑定到路由上面.它只会总路由上面的过滤器,全局的它不在走了