When one of my services fails, I aim to provide the correct HTTP status code back to the client.
Imagine a basic express app where a service getUserById(userId) {...}
is accessed from a controller. This service might fail due to various reasons such as an invalid user id, a bug in the code, or simply because the requested user does not exist.
In order to send back the appropriate HTTP status codes (400, 500, and 404), I would need to somehow include them with the error when it's thrown within my service. How can this be achieved and are there any recommended practices? Or maybe I have misunderstood something?
Currently, I handle it like this:
throw { message: 'No user with this ID exists', status: 404 }
However, I do realize that this approach may not be sustainable since it goes against the concept that one should stick to using standard errors only.