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 :
throw new Error()
, have the controller catch
them and then throw the appropriate kind of HttpException
(BadRequestException
, ForbiddenException
etc..)HttpException
.There are pros and cons to both approaches:
Error
for different reasons, how do I know from the controller which would be the corresponding kind of HttpException
to return?Http
related 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?
JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.
Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don't need to write your own to get started.
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; } })); } }
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.
Try it out in this codesandbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With