[Spring Boot] Setting up REST exception handling

Created on 26 Nov 2023

Exception handling in an application that exposes REST endpoints is a very important task that allows us to:

  • Set proper response status
  • Unify enpoints’ responses in case of expected and unexpected errors
  • Prevent exposure of unwanted information (carried with exception message)

In Spring it is very easy to handle exception that occurr while handling a REST request. To do that you can use AOP’s advices. Spring Web provides a ready to use annotations

  • @ControllerAdvice - wraps our controllers with an advice
  • @ExceptionHandler - creates a pointcut that filters requested types of exceptions. After successful match, annotated method will be executed as an exception handler.

Our job is to properly handle them and return proper data as a REST response. Below is a simple example of an exception handler that waits for any exception that occurred during the request processing and returns 500 Internal server response.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

@ControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(final Exception e) {
        return ResponseEntity
            .status(INTERNAL_SERVER_ERROR)
            .body("Unexpected error occurred.");
    }
}