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 :
- Have individual services and validation pipes
throw new Error(), have the controllercatchthem and then throw the appropriate kind ofHttpException(BadRequestException,ForbiddenExceptionetc..) - Have the controller simply call the service/validation pipe method responsible for handling that part of business logic, and throw the appropriate
HttpException.
There are pros and cons to both approaches:
- This seems the right way, however, the service can return
Errorfor different reasons, how do I know from the controller which would be the corresponding kind ofHttpExceptionto return? - Very flexible, but having
Httprelated stuff in services just seems wrong.
I was wondering, which one (if any) is the "nest js" way of doing it?
How do you handle this matter?