什么是nestjs错误处理方法(业务逻辑错误与http错误)? [英] What is the nestjs error handling approach (business logic error vs. http error)?

查看:993
本文介绍了什么是nestjs错误处理方法(业务逻辑错误与http错误)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用NestJS创建API时,我想知道哪种是处理错误/异常的最佳方法。
我找到了两种不同的方法:

While using NestJS to create API's I was wondering which is the best way to handle errors/exception. I have found two different approaches :


  1. 拥有单独的服务和验证管道抛出新的错误() ,让控制器 catch 然后抛出相应类型的 HttpException BadRequestException ForbiddenException 等..)

  2. 让控制器只需调用服务/验证管道方法负责处理该部分业务逻辑,并抛出相应的 HttpException

  1. Have individual services and validation pipes throw new Error(), have the controller catch them and than throw the appropriate kind of HttpException(BadRequestException, ForbiddenException etc..)
  2. Have the controller simply call the service/validation pipe method responsible for handling that part of business logic, and throw the appropriate HttpException.

两种方法都有利弊:


  1. 这似乎是正确的方式,但服务可以返回错误由于不同的原因,我如何从控制器中知道要返回的相应类型的 HttpException

  2. 非常灵活,但服务中的 Http 相关内容似乎有误。

  1. This seems the right way, however, the service can return Error for different reasons, how do I know from the controller which would be the corresponding kind of HttpException to return?
  2. Very flexible, but having Http related stuff in services just seems wrong.

我在想,哪一个(如果有的话)是nest js的做法吗?

I was wondering, which one (if any) is the "nest js" way of doing it ?

你如何处理这件事?

推荐答案

假设您的业务逻辑抛出 EntityNotFoundError ,并且您希望将其映射到 NotFoundException

Let's assume your business logic throws an EntityNotFoundError and you want to map it to a NotFoundException.

为此,您可以创建一个 拦截器 可以改变您的错误:

For that, you can create an Interceptor that transforms your errors:

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // next.handle() is an Observable of the controller's result value
    return next.handle()
      .pipe(catchError(error => {
        if (error instanceof EntityNotFoundError) {
          throw new NotFoundException(error.message);
        } else {
          throw error;
        }
      }));
  }
}

然后您可以通过添加<$ c $来使用它c> @UseInterceptors(NotFoundInterceptor)到你的控制器的类或方法;甚至作为所有路线的全球拦截器。当然,您也可以在一个拦截器中映射多个错误。

You can then use it by adding @UseInterceptors(NotFoundInterceptor) to your controller's class or methods; or even as a global interceptor for all routes. Of course, you can also map multiple errors in one interceptor.

codesandbox

这篇关于什么是nestjs错误处理方法(业务逻辑错误与http错误)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆