#wondering the best way to handle errors in NestJS (not microservices)

6 messages · Page 1 of 1 (latest)

grave raft
#

Hi, I'm a beginner backend developer from South Korea studying to become a good developer.

I was wondering the best way to handle errors in NestJS (not microservices). REST API

The way I'm handling it now, is to handle exceptions at the service layer, catch them with a filter and respond in a common format.

https://github.com/nestjs/nest/issues/310

Based on that link, I was thinking about shekohex's solution, but I don't think the code would be clean as there would be a lot of try catches between the repository layer, service layer, and controller layer.

Also, it is said that it is not allowed to throw a NotFoundException directly from the service layer when there is no record inside the database.

So I'm curious to hear your methods or opinions on where and how to handle the exception.

P.S.
If there are any grammatical errors or poor word choices in what I have written, please be understanding. 🥹

GitHub

Hi all, I would like to know what is the best practice to send an HttpException. Can throw it on service or it's better to do this in the controller ? Thx

pulsar frigate
storm cliff
#

My two cents. Throw errors early, catch them late. I'm not sure about the problem. I would try to stick to the NestJS error handling as much as possible.

old delta
lunar gate
#

Exceptions are ok to handle exceptional errors. I personally don't like the NestJS way to rely on exceptions to control the normal flow of an application.

For example, it should be part of the expected behavior of a REST API to return a status 400 response when the client send a bad request. This is not an exceptional error so it shouldn't be handled using exceptions.

That said, the mechanism that offers NestJS for error handling is based on exceptions. If you are a beginner is probably best to stick to the framework conventions or bring the problem to the more experienced members of your team.

In our team we made our own error handling mechanism so we don't have to rely on Exceptions for non-exceptional errors.

edgy crypt
#

It's a good practice not to throw NotFoundException in service layer because that method could be used by some other module or service and you may not want to throw exception there. I usually throw not found exception for get endpoints inside the controller. As for your first question, you should not put try and catch all over the place. Majority of the time, unexpected exceptions should not happen anyway. NestJS default exception handler was almost always good enough for me. There are exceptional cases where try and catch might be useful but you should not use it in all the service methods