Use `@ControllerAdvice` with `@ExceptionHandler` to map exceptions to consistent HTTP responses (status + body). It keeps controllers clean and centralizes error handling.
@ControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<String> badRequest(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}Global exception handling in Spring MVC is commonly done with:
You map exception types to HTTP responses using `@ExceptionHandler`. For rich responses, return `ResponseEntity<?>` (status, headers, body) or use `ProblemDetail` in newer Spring versions.
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<ProblemDetail> badRequest(IllegalArgumentException e) {
var pd = ProblemDetail.forStatus(400);
pd.setTitle("Bad request");
pd.setDetail(e.getMessage());
return ResponseEntity.badRequest().body(pd);
}
}