阅读提示:本文共计约3364个文字,预计阅读时间需要大约9分钟,由作者office2010破解版编辑整理创作于2023年11月06日15时07分28秒。

在 NestJS 中,我们可以通过使用全局异常处理中间件(Exception Filters)来实现对所有错误和异常的统一处理。对于 @Injectable 的 service,我们可以在其方法上添加 @UseFilters(new CustomExceptionFilter()) 注解来指定使用的自定义异常过滤器。

在NestJS中实现对@Injectable服务中错误的统一处理

以下是一个简单的示例:

  1. 创建一个自定义异常过滤器类 CustomExceptionFilter
import { ExceptionFilter, ArgumentsHost, HttpException } from '@nestjs/common';

export class CustomExceptionFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.res;
    const status = exception instanceof HttpException ? exception.getStatus() : 500;

    // 在这里处理你的错误响应
    response.status(status).json({
      statusCode: status,
      message: 'An error occurred',
      error: {}, // 这里可以填充具体的错误信息
    });
  }
}
  1. 在需要使用该自定义异常过滤器的 service 的方法上添加 @UseFilters(new CustomExceptionFilter()) 注解:
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  @UseFilters(new CustomExceptionFilter())
  async doSomethingThatMightThrowError() {
    // 可能会抛出错误的代码
  }
}

这样,当 MyServicedoSomethingThatMightThrowError 方法抛出任何错误时,都会由 CustomExceptionFilter 进行处理,返回统一的错误响应。

点赞(12) 打赏

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部