Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-21

What is the role of @ControllerAdvice with @ExceptionHandler?

Options

  1. It authenticates the users before each controller call
  2. It centralizes exception handling and HTTP error replies (Correct option)
  3. It schedules tasks to run at fixed times of the day
  4. It logs every SQL statement that the app executes

Answer

It centralizes exception handling for all controllers, converting exceptions into consistent HTTP error responses

Why

Without it, an uncaught exception in a controller becomes a generic 500 error. With @RestControllerAdvice you write one class that catches exceptions from every controller and returns a clean JSON body with the right status code (404 for "not found", 400 for validation, 409 for conflicts...).

It keeps controllers free of try/catch and gives clients a predictable error format.

@RestControllerAdvice
public class ApiErrors {
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<Map<String, String>> notFound(UserNotFoundException e) {
        return ResponseEntity.status(404).body(Map.of("error", e.getMessage()));
    }
}

Remember

One @RestControllerAdvice class = consistent error responses.

Key terms

Practice this question in Repaso