0

I use @ControllerAdvice to catch exceptions in my Spring Boot controller. In @ExceptionHandler I can manually specify limited number of exception with their status codes.

My question is how I can deal with every other exception and their statuses?

I can specify some exceptions with their statuses like this:

@ExceptionHandler(MethodArgumentNotValidException.class)
 public ResponseEntity<Object> argNotValidExceptionHandler(MethodArgumentNotValidException ex){
    String localizeMessage = ex.getLocalizeMessage();

    ErrorMessage errorMessage = new ErrorMessage(LocalDateTime.now(), localizeMessage);

    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}

As I would like to catch all exceptions it seems I should additionally specify Exception.class with a status INTERNAL_SERVER_ERROR in @ExceptionHandler.

At this point I will get status 500 for all other exceptions even with 4** statuses.

How I can produce proper status code from every exception to send it to a client?

Ebrahim Pasbani
  • 9,168
  • 2
  • 23
  • 30
Kirill Ch
  • 5,496
  • 4
  • 44
  • 65

1 Answers1

0

You can create custom exception classes and while defining these custom exception class, configure http status code that should be sent in case this exception occurs. So when you caught this exception the exception handler, you can get the http status code that should be returned to user from exception and send the same.

Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30