Search code examples
javaspring-boothttp-status-codesspring-restcontroller

Spring boot - custom rest controller exception handling HTTP status


I have created a custom REST Controller Exception Handler for my spring boot application ...

@ControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionHandler {    
  @ExceptionHandler(TechnicalException.class)
  public ResponseEntity handleTechnicalException(TechnicalException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(BusinessException.class)
  public ResponseEntity handleBusinessException(BusinessException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(ValidationException.class)
  public ResponseEntity handleValidationException(ValidationException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getDetails()), BAD_REQUEST
    );
  }
}

... where I handle validation, business (exceptions that caused because of violation of business rules) and technical (database related, invalid request parameters, etc.) exceptions.

The exception classes have two parameters: errorCode (unique enum) and message (exception details).

As you can see from the example, for all cases I return BAD_REQUEST (400) status, which is not the best practice.

I would like to know the best way to handle HTTP statuses based on the exception category, for example: for validation errors returning BAD_REQUEST (400) status is "okay".

... or is there any way which lets spring-boot "decides" which status code to send?


Solution

  • From java & spring side, use @ControllerAdvice and @ExceptionHandler is a best practice.

    From values of error codes, there is no standard. But you could:

    1. Follow the old https code status standard

    • 1xx informational response – the request was received, continuing process
    • 2xx successful – the request was successfully received, understood and accepted
    • 3xx redirection – further action needs to be taken in order to complete the request
    • 4xx client error – the request contains bad syntax or cannot be fulfilled
    • 5xx server error – the server failed to fulfill an apparently valid request

    2. Copy from World Class Companies

    https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes

    3. Implement your own codes without collide the http old standards

    https://developer.paypal.com/docs/classic/api/errors/#10000-to-10099