Global Exception Handling with @ControllerAdvice
Centralize exception translation into clean HTTP responses using @ExceptionHandler and @ControllerAdvice.
Why Centralize Exception Handling?
When something goes wrong in a Spring Boot REST API, the client should receive a clean, predictable HTTP response, not a raw stack trace.
Without a strategy, you end up scattering try/catch blocks across every controller method, repeating the same JSON-building logic over and over.
- Inconsistent status codes for the same error type
- Duplicated error-response shaping
- Leaked internal details (stack traces, SQL) to clients
Global exception handling solves this by translating exceptions into HTTP responses in one place.
The @ExceptionHandler Building Block
The core annotation is @ExceptionHandler. It marks a method that handles a specific exception type thrown during request processing.
Placed inside a controller, it only catches exceptions thrown by that controller's handler methods.
The method's parameter declares which exception it handles, and its return value becomes the HTTP response.
@RestController
public class ProductController {
@GetMapping("/products/{id}")
public Product getProduct(@PathVariable Long id) {
throw new ProductNotFoundException(id);
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<String> handleNotFound(ProductNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}All lessons in this course
- Bean Validation Constraints and Constraint Groups
- Building Custom Constraint Annotations
- Global Exception Handling with @ControllerAdvice
- RFC 7807 Problem Detail Responses