Web error handling concept
Table of content
- Defining the goals of the concept
- Defining how errors are transmitted
- Handling errors in the backend
- Transferring error to the frontend
- Handling errors in the frontend
- Conclusion
Defining how errors are transmitted
When an error occurs, we want to send information to the frontend about what the user should see, rather than what happened. As previously mentioned, we will add error codes and error messages.
The error code is a constant, which the frontend should be capable of mapping to a message for the user that can also be translated.
The error message is a fallback message. Usually, it should not be displayed to the user, but should only be shown when the frontend hasn't defined the message for a specific error code (no matter the reason). This way, we don't have to do such things as showing the error code.
So, when a server response has a 4xx or 5xx HTTP status code, it should look something like this:
{
"errorCode": "REGISTRATION_EMAIL_INVALID",
"error": "The email for the registration is not valid"
}
First, we have an errorCode field, which we can now map to a message the user should see. In this case, the user seems to have entered an invalid email. So the mapping could be something like "Please enter a valid email address".
Second, I named the field "error" instead of "errorMessage". The reason for this is that often in other code examples "response.error" is logged. To make it more intuitive, I decided to use "error" instead of "errorMessage", but feel free to name the fields of your interface definition as you want.
Third, I can read the message (e.g., as a developer, or as a user who reads this as a fallback message) and see that there seems to be something wrong with what I have entered as my email address.