Why Centralized Exception Handling Matters
Without explicit handling, an uncaught exception in a Spring Boot controller results in a generic 500 Internal Server Error with Spring Boot's default Whitelabel Error Page or a bare JSON error body, exposing little useful information to API consumers and potentially leaking stack traces in non-production configurations. Centralized exception handling lets you map specific exception types to specific HTTP status codes and consistent, structured error bodies across your entire API, rather than scattering try-catch blocks through every controller method.
Cricket analogy: It's like having a single, trained match referee handle all disputes consistently across every game, instead of each umpire on the field making up their own rules for what counts as an appeal — centralized handling keeps error responses consistent.
@ExceptionHandler and @ControllerAdvice
@ExceptionHandler, placed on a method, tells Spring to invoke that method whenever a specified exception type (or subtype) is thrown within the same controller. To apply this handling globally across all controllers rather than duplicating it per class, combine it with @ControllerAdvice (or @RestControllerAdvice, which adds implicit @ResponseBody) on a dedicated class. Spring matches the most specific exception type first, so a handler for IllegalArgumentException takes precedence over a broader handler for Exception when both could apply.
Cricket analogy: Like the ICC's central code of conduct that applies across every international match, rather than each cricket board writing its own disciplinary rules — @ControllerAdvice centralizes handling the same way.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
ErrorResponse body = new ErrorResponse("NOT_FOUND", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
String message = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.collect(Collectors.joining("; "));
return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", message));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
return ResponseEntity.internalServerError()
.body(new ErrorResponse("INTERNAL_ERROR", "Unexpected error occurred"));
}
}Custom Exceptions and Meaningful Status Codes
Rather than throwing generic RuntimeException everywhere, define custom exception classes such as ResourceNotFoundException or DuplicateEmailException that carry semantic meaning about what went wrong. Each custom exception maps cleanly to a specific HTTP status in its handler — 404 for not-found, 409 for conflicts, 400 for bad input — which makes API behavior predictable for consumers and keeps service-layer code expressive: throwing new ResourceNotFoundException("Order " + id) reads far better than a raw RuntimeException with a string message.
Cricket analogy: Like distinguishing a 'run out' from a 'stumping' from a 'caught behind' on the scorecard instead of just logging 'batsman is out' — each specific dismissal type carries distinct meaning, just as each custom exception maps to a distinct status.
Spring Boot 3's ProblemDetail (RFC 7807) class is a built-in alternative to hand-rolled error DTOs. Returning ResponseEntity<ProblemDetail> from an @ExceptionHandler gives you a standardized error format (type, title, status, detail, instance) out of the box.
Never let an @ExceptionHandler(Exception.class) leak raw exception messages or stack traces to the client in production — these can reveal internal class names, SQL fragments, or file paths. Log the full exception server-side and return a generic, safe message to the caller.
- Uncaught exceptions default to a generic 500 error unless explicitly handled.
- @ExceptionHandler maps a specific exception type to custom response logic within a controller.
- @RestControllerAdvice applies exception handling globally across all controllers, with implicit @ResponseBody.
- Spring resolves the most specific matching exception handler first.
- Custom exception classes (ResourceNotFoundException, DuplicateEmailException) carry semantic meaning tied to specific HTTP statuses.
- Spring Boot's built-in ProblemDetail class offers a standardized RFC 7807 error response format.
- Never expose raw stack traces or internal error details to API clients in production.
Practice what you learned
1. What is the purpose of @ControllerAdvice (or @RestControllerAdvice)?
2. If handlers exist for both IllegalArgumentException and Exception, which one handles a thrown IllegalArgumentException?
3. What is Spring Boot's built-in RFC 7807 error response type?
4. Why is it risky to let a generic Exception handler return the raw exception message to the client?
5. What happens by default when a controller method throws an unhandled exception?
Was this page helpful?
You May Also Like
Validation in Spring Boot
Learn how to validate incoming request data in Spring Boot using Bean Validation annotations, @Valid, and custom validators.
Building REST Controllers
Learn how to build REST controllers in Spring Boot using @RestController, structure methods cleanly, and return well-formed HTTP responses.
Request and Response Bodies
Learn how Spring Boot serializes and deserializes JSON request and response bodies using @RequestBody, @ResponseBody, and Jackson.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics