node-express-boilerplate icon indicating copy to clipboard operation
node-express-boilerplate copied to clipboard

Throwing ApiError from service

Open FrazCake opened this issue 5 years ago • 4 comments

HI @hagopj13, first of all thank you for this boilerplate, it's very useful. I'm not an expert, but I have a question related to error throwing. Is it a good practice to throw specific error like ApiError from the service layer? I always thought that this kind of error belong to the controller, while the service shouldn't know that the caller is talking using HTTP. Am i wrong? Thank you.

FrazCake avatar Sep 09 '20 07:09 FrazCake

@FrazCake thanks for your suggestion. You have a point. I tried to minimize the ApiErrors coming from the services layer as much as possible. But there are some cases where I would like to return a different error (and a different error code) within the same service, depending on what went wrong (like in the case of updateUserById in the user service). I can extract the different cases into separate services and call them from the controller and handle the error of each one separately, but then I would be putting more business logic in the controllers (which is the whole point behind why the services layer is there).

I will give this some more thought and try to find a more optimal way. If you already know how to do it, please feel free to contribute.

hagopj13 avatar Sep 09 '20 12:09 hagopj13

It looks to me like simple cosmetics. Use common errors and use the error.js::errorHandler to convert into ApiError to return the proper response.

On another note @hagopj13 I would like to take this opportunity to thank you so much for your work, efforts and gratitude to place this boilerplate as open source. I did an entire functional working API in two days. Thank you so much.

tonydspaniard avatar Nov 03 '20 11:11 tonydspaniard

Oi

hacker8-eng avatar Apr 05 '21 16:04 hacker8-eng

It looks to me like simple cosmetics. Use common errors and use the error.js::errorHandler to convert into ApiError to return the proper response.

On another note @hagopj13 I would like to take this opportunity to thank you so much for your work, efforts and gratitude to place this boilerplate as open source. I did an entire functional working API in two days. Thank you so much.

@tonydspaniard can you give an example?

vmundhra avatar May 09 '22 20:05 vmundhra