Setting http response code Vs throwing HTTP exception in NestJs

39 Views Asked by At

I encountered a situation where I was not sure how to handle errors that occure in my program. let's say for example situation where I have a custom error that gets thrown from the business layer and I want to catch it before the response gets to the client to change the status code of the response.

So, to implement it, I found 3 solutions:

  1. I can catch the custom error in the controller and replace it with an HTTP Exception from nestJs, with a simple try-catch clause in a controller function.
  2. Another option for handling it do it in the BL which I don't prefer because then the BL would be aware that I have REST API, I would want to keep it unaware of this behavior, so that is why it is not relevant for me.
  3. Using exception filters, but one thing that I did not like using this method and I would like to hear opinions for it too, is that I have to change the response manually, and its status code because when I tried to throw for example NotFoundException from at the exception filter it did not change the response.

Another interesting problem could be a process that receives an object and during it the BL discovers that it does not comply with certain rules that I imply on this object for example, the object must contain a field named: name and it must be a string value.

So same as before we can detect it in the BL, or another option could be using a middleware of some kind and rejecting it even before it reaches the controller, would you say it is preferable to do it there and if so what tool would you use to do it (interceptor/guard/validation pipe/etc..)

0

There are 0 best solutions below