node-express-boilerplate
node-express-boilerplate copied to clipboard
Throwing ApiError from service
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 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.
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.
Oi
It looks to me like simple cosmetics. Use common errors and use the
error.js::errorHandlerto 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?