#Error Handling in a Nest Application

4 messages · Page 1 of 1 (latest)

calm folio
#

Say I have a nest.js backend which connects to Prisma, Redis, and do Http Requests using Fetch.

Every one of these external integrations are made behind a Service class like PrimaService, RedisService, HttpService, etc.

But each one of these integrations can throw a lot of different Error objects, for example, a PrismaService.findUser() method can throw an Error if it does not find the user, and a different one if the Database connection failed for example.

And say I have a Users.getCurrentUser() method which uses this PrismaService.findUser() method, and I want to throw different error responses and status codes, based on my PrismaService response. (a 404 if it does not find the user, and a 500 with a custom error message if the DB is down, for example)

I know I can do something like this is the function that calls my service like Users.getCurrentUser():


    try {
      await this.prismaService.getUser({
        name: user.name,
      });
    } catch (error) {
      if (
        error?.message?.includes(
          'the prisma library text error message for not found',
        )
      ) {
        throw new NotFoundException('User is not found by this name', { "cause": error });
      } else {
        throw error;
      }
    }
  }
}

But it does not look right, because in each Service class call I will need to try catch, just to throw a new Exception and move on.

It looks like there can be a custom Exception Handler into Nest, but I don't want to replace the default one, I don't know how to implement something (maybe a response interceptor?) that can do the if part of an error, and throw a custom error response, preferably using the native NotFoundException, InternalServerErrorException methods that Nest have built-in.

Does someone have an example how to do that? how do you guys solve this in problem in your apps? thanks!

dim nymph
#

Nest js have made a provision for that through the use of exception filters

you can get more details here
https://docs.nestjs.com/exception-filters

you can create an exception filter to handle the errors globally or for prisma errors.

full raven
#

I don't like Exception Filters because they are too close to the response object and if you are not familiar with it you can screw up. I prefer to handle exceptions in interceptors and they can work on different contexts than http too. But in general using try catch to update the context of the exception is not that bad. Just service didn't know where it is executed inside http context so I wouldn't use Nest errors in services

frail sun
#

@full raven do you have some public repos that can show your recommendations?