What is the role of @ControllerAdvice with @ExceptionHandler?
Options
- It authenticates the users before each controller call
- It centralizes exception handling and HTTP error replies (Correct option)
- It schedules tasks to run at fixed times of the day
- 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.