Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the nestjs error handling approach (business logic error vs. http error)?

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. Have individual services and validation pipes throw new Error(), have the controller catch them and then 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.

There are pros and cons to both approaches:

  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.

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

How do you handle this matter?

like image 954
Aaron Ullal Avatar asked Jun 30 '18 07:06

Aaron Ullal


People also ask

What is error handling in JS and how can use it?

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.

What is error handling in Express JS?

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.


1 Answers

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.

like image 78
Kim Kern Avatar answered Sep 24 '22 11:09

Kim Kern