Nestjs 中定义既可以捕获错误(Error)和又可以异常(Exception)的过滤器

Nestjs 中,使用基于 HttpException 定义过滤器的话,只能捕获 Http 带状态码(statusCode)的 Exception,不能捕获 throw new Error(‘xxx’) 抛出的错误。

以下是使用实现 ExceptionFilter 接口定义的一个不特定于平台(express 或 fastify,即无论使用这两个web服务框架的其中一个都可以)的,可以捕获所有错误(Error)和异常(Exception)的全局错误/异常过滤器。
1、在项目的根目录的 config 目录 下创建 all-exceptions.filter.ts 文件,内容如下:
// all-exceptions.filter.ts

/**
 *  定义捕获所有异常(Exception)和 错误(Error)
 *  的全局异常/错误过滤器,需在 app.module.ts 中注册该过滤器
 */

import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import { HttpAdapterHost } from "@nestjs/core";
import { Request, Response } from "express";

// 导入格式化日期时间的第三方工具包
import * as dayjs from 'dayjs';


@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
    constructor(private readonly httpAdapterHost: HttpAdapterHost) { }

    catch(exception: any, host: ArgumentsHost) {
        console.log('AllExceptionsFilter exception:', exception);
        const { httpAdapter } = this.httpAdapterHost;
        const ctx = host.switchToHttp();
        const request = ctx.getRequest<Request>();
        const response = ctx.getResponse<Response>();
        const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        const resContents = {
            status: statusCode,
            cause: exception?.cause,
            errName: exception?.name,
            message: exception?.message,
            time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            // stack: exception?.stack,
            path: httpAdapter.getRequestUrl(request),
        }

        // 使用不特定于平台(express 或 fastify)的方式(httpAdapter)返回响应内容
        httpAdapter.reply(response, resContents, statusCode);
    }
}
2、把以上定义的注册为全局的错误/异常过滤器

2.1、方法一:在 main.ts 中注册为全局的错误/异常过滤(此方式不支持依赖注入)

// main.ts

...
import { AllExceptionsFilter } from './common/all-exceptions.filter.ts';
...
app.useGlobalFilters(new AllExceptionsFilter());
...

2.2、方法二(推荐):在 app.module.ts 中的 @Module 装饰器中的 providers 节点作为提供器注入

// app.module.ts

...
import { AllExceptionsFilter } from './common/all-exceptions.filter.ts';
...
@Module({
  ...
  providers: [
    {
      provide: 'APP_FILTER',
      useClass: AllExceptionsFilter
    }
  ],
  ...
})

(完)

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值