Exception Handling in a Web Project
Exception handling is a common function in a web project. In this post, I will cover the basic principles of how to do exception handling in a web project.
The Process
- Create an ErrorEnum to represent your error codes and messages.
- Create a custom Exception class. The class has an ErrorEnum type field.
- Create an Exception or Error object and pass an ErrorEnum to the constructor.
- Throw the error object in somewhere.
- The global exception handler processes the error.
- Get the value of the ErrorEnum type field from the error object. And convert the ErrorEnum to an error model.
- Set a appropriate HTTP response status code.
- Return the error model to the client.
Details
ErrorEnum: To represent error code and messages
Principles
- Put all code and messages in a single file or single directory. It’s easy to maintain.
- Using string or number to represent error code. I prefer using string.
- Error messages may need to use internationalization (i18n).
In Java, you can use an enum to do this. For example:
public enum ErrorEnum { |
Custom exception class: Support to throw a custom exception object
It’s a custom Exception class that has an ErrorEnum field.
Global exception handler: Handle uncaught exceptions
It sets an appropriate HTTP response status code and responds to an error model object as a JSON.
Error model: a POJO to pass the error information
It’s a POJO class that has errorCode and errorMessage fields.
Appendixes
Common HTTP response status codes
| Status code | Description |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 405 | Method Not Allowed |
| 408 | Request Timeout |
| 500 | Internal Server Error |
| 502 | Bad Gateway |
| 504 | Gateway Timeout |