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!