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

  1. Create an ErrorEnum to represent your error codes and messages.
  2. Create a custom Exception class. The class has an ErrorEnum type field.
  3. Create an Exception or Error object and pass an ErrorEnum to the constructor.
  4. Throw the error object in somewhere.
  5. The global exception handler processes the error.
    1. Get the value of the ErrorEnum type field from the error object. And convert the ErrorEnum to an error model.
    2. Set a appropriate HTTP response status code.
    3. 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 {

SYSTEM_ERROR("INTERNAL_SYSTEM_ERROR", "Internal system error"),

USER_OR_PASSWORD_ERROR("USER_OR_PASSWORD_ERROR", "Username or password is incorrect"),

BAD_REQUEST("BAD_REQUEST", "Bad request"),

METHOD_NOT_ALLOWED("METHOD_NOT_ALLOWED", "Request method not allowed"),

PARAM_ERROR("PARAM_ERROR", "Parameter error"),

DUPLICATE_SUBMIT("DUPLICATE_SUBMIT", "Please do not submit the form repeatedly")
;

private String errorCode;
private String errorMessage;

ErrorEnum(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}

public String getErrorCode() {
return errorCode;
}

public String getErrorMessage() {
return errorMessage;
}

@Override
public String toString() {
return "ErrorEnum{" +
"errorCode='" + errorCode + '\'' +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}

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