第十七章 自定义ExceptionFilter

在nestjs中,Exception Filter(异常过滤器)是用于处理全局异常的一种机制。它可以捕获应用程序中发生的异常,并对其进行统一处理。本章我们来学习自定义Exception Filter。

首先 先创建一个新的项目:

nest new exception-filter

1719630765771.png
启动项目:

npm run start:dev

1719634571168.png
在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 其实就是内置的一些状态码
1719636411087.png
此时 游览器访问 http://localhost:3000/ 可以看到返回的响应是400
1719636511371.png
以上返回的响应格式是内置 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/
1719636798754.png
接着我们定义一个 exception filter:

nest g filter test --flat --no-spec

1719636975288.png
修改 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 =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枫ゞ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值