bulletproof-nodejs
bulletproof-nodejs copied to clipboard
Question: How to handle multiple exceptions throwed by Services?
I read your article and checked your pattern and I was surprised that my architecture is very similar to yours. But I not found one thing I am searching for quite for a while:
How to handle more errors from Service? For example I have Service User
with method activateUser
. This method recieve activation token
and based on token's validity (user not already active, token exists, token not expired, user exists) I activate user or not.
The problem is that there is lot of things what can go wrong and throwing just one type of error is not good for clients. I am using i18n so I am translating keys to texts inside my controller.
Should I just throw those keys from my Service?
Now I am just trying to have every service method to do one thing so I can throw 1 error. But then I am moving too much stuff into controller:
- Does user exists?
If not throw
not exists
error - Is user already active?
If not throw
already active
error - Is token not expired?
If not throw
token expired
error - Does database update failed?
If not throw
error while saving
error
This is just example and I have much more of this trough project, where I have controller full of one-time-use services because I need to return different error messages for each one of them.
Hope you understand my frustration and have some more expirience what you can share :)
There is also another problem, u should able to map errors/exceptions to relevant response code. Someone(controller?) should know how to map them to relevant response code... Doing it by "message" not a best way, so I guess every error or group of errors(exceptions) should have an identifier.