在nestjs中,Exception Filter(异常过滤器)是用于处理全局异常的一种机制。它可以捕获应用程序中发生的异常,并对其进行统一处理。本章我们来学习自定义Exception Filter。
首先 先创建一个新的项目:
nest new exception-filter
启动项目:
npm run start:dev
在controller 里抛个异常,修改app.controller.ts:
import {
Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import {
AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {
}
@Get()
getHello(): string {
throw new HttpException('xxxxx', HttpStatus.BAD_REQUEST)
return this.appService.getHello();
}
}
HttpStatus 其实就是内置的一些状态码
此时 游览器访问 http://localhost:3000/ 可以看到返回的响应是400
以上返回的响应格式是内置 Exception Filter 生成
同时 也可以直接抛出具体的异常
import {
BadRequestException, Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import {
AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {
}
@Get()
getHello(): string {
// throw new HttpException('xxxxx', HttpStatus.BAD_REQUEST)
throw new BadRequestException('异常');
return this.appService.getHello();
}
}
继续游览器访问 http://localhost:3000/
接着我们定义一个 exception filter:
nest g filter test --flat --no-spec
修改 test.filter.ts:
import {
ArgumentsHost, BadRequestException, Catch, ExceptionFilter } from '@nestjs/common';
@Catch(BadRequestException)
export class TestFilter implements ExceptionFilter {
catch(exception: BadRequestException, host: ArgumentsHost) {
const http = host.switchToHttp()
const response =