Throughout my software and web development career, there are some patterns that I noticed regarding error handling that surfaces every time. Here I’m going to share some of my favorite tips to make error handling less painful.
Return error codes in your API
Return error codes as opposed to returning only a message in your responses.
Why you might ask? Isn’t it easier to just return a message instead of having to map your exception/return values to a error code in the backend?
The reason is that a simple message is never enough to handle what you need to present on the UI.
- What if someone asks you to bold a word in the middle of the message? Are you going to return HTML in that case?
- What if you a have a list of items or errors that you want to format into a bulleted list? You wouldn’t be able to combine everything together in one long line!
How would you accomplish any of the above? It’s not possible to do this without putting in an less than ideal solution. Error codes like the following are the answer.
{
code: 'authorization_error'
message: 'You are not authorized to access this application.'
}
Your client side code can simple do a switch on all the possible codes and display whatever it wants, making your app all the more flexible to style these messages for readability and usability.