Spring Boot is widely used in the development of microservices. In this article, we will see how we can perform exception handling of exposed endpoints in a Spring Boot application. We will go through three different ways to handle exceptions.
Exception Handler (@ExceptionHandler)
In this approach you can define a method in your controller class annotating it with @ExceptionHandler annotation. This method will be activated as soon any of the API method throws the defined exception. One limitation with this approach is you need to create such methods in every controller(@Controller or @RestController) class.
Example:
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException() {
  return ResponseEntity.internalServerError().body("Unknown error");
}
Controller Advice (@ControllerAdvice)
To overcome the above limitation, we can use @ControllerAdvice. In this approach, you will define a class and annotate it with @ControllerAdvice, and then you will move your method (marked with @ExceptionHandler) inside this class. It will catch defined exception thrown by any controller (@Controller or @RestController) and gives developer option to manage exception handling of different controllers in a single class.
Example:
@ControllerAdvice
class ExceptionsController {
  @ExceptionHandler(CustomException.class)
  public ResponseEntity<String> handleCustomException() {
    return ResponseEntity.internalServerError().body("Unknown error");
  }
}
Response Status (@ResponseStatus)
This approach also gives you similar flexibility as Controller Advice. In this, instead of creating a separate class you will mark your exception class with @ResponseStatus annotation.
Example:
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Unknown error, Team is looking into the issue")
class CustomException extends Exception {
}
* In order to support this annotation to display reason you need to add below entry in your application configuration (application.properties).
server.error.include-message=always

