EzyHTTP Handle Exceptions

EzyHTTP provides 3 way to help you handle exception easily

1. Use default exception

EzHTTP provides to you some default Http exceptions related to HTTP Error codes:
  • HttpBadRequestException: 400 - Bad Request
  • HttpUnauthorizedException: 401 - Unauthorized
  • HttpForbiddenException: 403 - Forbidden
  • HttpNotFoundException: 404 - Not Found
  • HttpMethodNotAllowedException: 405 - Method Not Allowed
  • HttpNotAcceptableException: 406 - Not Acceptable
  • HttpRequestTimeoutException: 408 - Request Timeout
  • HttpConflictException: 409 - Confict
  • HttpUnsupportedMediaTypeException: 415 - Unsupported Media Type
  • HttpInternalServerErrorException: 500 - Internal Server Error
Or you can throw HttpRequestException if you want to response other codes and data.
For example, in this case if the book's name length is longer than MAX_NAME_LENGTH, EzyHTTP will return to client Status 400 and message name length must < {max value}:
public void validate(AddBookRequest request) {
    if (request.getBookName().length() > MAX_NAME_LENGTH) {
        throw new HttpBadRequestException("name length must < " + MAX_NAME_LENGTH);
You can find out full source code in BookValidator example.

2. Handle exception in a controller

If your exception only happends in a controller scope, you should handle it in that controller like this:
public class CategoryController {
    // request handler methods

    public ResponseEntity handle(CategoryNotFoundException e) {
        return ResponseEntity.notFound(
            Collections.singletonMap("category", "notFound")
You can find out full source code in CategoryController example.

3. Handle exceptions in a global handler

If your exceptions happend in many controller, and you want to save time and avoid source code duplication, you can create a global handler class to handle that exceptions like this:
public class GlobalExceptionHandler extends EzyLoggable {

    public ResponseEntity handleException(
        IllegalArgumentException e
    ) {
        logger.info("invalid argument: {}", e.getMessage());
        return ResponseEntity.badRequest(e.getMessage());

    public ResponseEntity handleException(
        NotFoundException e
    ) {
        logger.info("not found: {}", e.getMessage());
        return ResponseEntity.notFound(e.getMessage());
You can find out full source code in GlobalExceptionHandler example.

4. Next