问题描述
在使用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 :
- 拥有单独的服务和验证管道
抛出新的错误()
,让控制器catch
然后抛出相应类型的HttpException
(BadRequestException
,ForbiddenException
等..) - 让控制器只需调用服务/验证管道方法负责处理该部分业务逻辑,并抛出相应的
HttpException
。
- Have individual services and validation pipes
throw new Error()
, have the controllercatch
them and than throw the appropriate kind ofHttpException
(BadRequestException
,ForbiddenException
etc..) - Have the controller simply call the service/validation pipe method responsible for handling that part of business logic, and throw the appropriate
HttpException
.
两种方法都有利弊:
- 这似乎是正确的方式,但服务可以返回
错误
由于不同的原因,我如何从控制器中知道要返回的相应类型的HttpException
? - 非常灵活,但服务中的
Http
相关内容似乎有误。
- 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 ofHttpException
to return? - 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.
在。
这篇关于什么是nestjs错误处理方法(业务逻辑错误与http错误)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!