The 30 second answer
I put the error handling in one class annotated with @RestControllerAdvice, with an @ExceptionHandler method for each exception type. Each handler maps the exception to the right status and a consistent error body. Spring 6 supports ProblemDetail, the standard RFC 9457 error format, so clients always get type, title, status and detail. That keeps try-catch out of controllers and never leaks stack traces to clients.
<!-- level: 1 --> <!-- must_know: true -->
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail notFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
return problem;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
problem.setTitle("Validation failed");
problem.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage()).toList());
return problem;
}
}@ExceptionHandlermethods handle exceptions thrown by controller methods. Inside one controller they apply to that controller; inside a@ControllerAdvice(or@RestControllerAdvice, which adds@ResponseBody) they apply to all controllers.- Spring Framework supports RFC 9457 problem details with
ProblemDetailandErrorResponse, so every error has the same JSON shape. Spring Boot can turn this on for its built-in exceptions withspring.mvc.problemdetails.enabled=true. - Good practice: map each domain exception to one status, log unexpected exceptions once with the request ID, and return a generic
500message without a stack trace.
The deeper question on how Spring translates exceptions internally is How does Spring Boot handle exception translation?.
Sources (3)
- Spring Framework: Exceptions (@ExceptionHandler)docs.spring.io
- Spring Framework: Controller advicedocs.spring.io
- Spring Framework: Error responses (RFC 9457 problem details)docs.spring.io