Spring Boot: From Basics to Production · Validation and Error Handling
Global Error Handling with Problem Details
Return RFC 9457 Problem Details consistently with @RestControllerAdvice.
Spring supports RFC 9457 Problem Details (ProblemDetail, application/problem+json). Enable it for built-in exceptions with spring.mvc.problemdetails.enabled=true, and map your own domain exceptions in a @RestControllerAdvice (optionally extending ResponseEntityExceptionHandler). Include a stable type, a human-readable title/detail, and extra properties like field errors — never stack traces.
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NotFoundException.class)
ProblemDetail notFound(NotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
pd.setType(URI.create("https://api.example.com/problems/not-found"));
pd.setTitle("Resource not found");
return pd;
}
@ExceptionHandler(InsufficientStockException.class)
ProblemDetail conflict(InsufficientStockException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
pd.setProperty("sku", ex.sku());
pd.setProperty("available", ex.available());
return pd;
}
}
Common pitfalls
- Different error formats per controller.
- Catching
Exceptionand returning 200 with an error message. - Exposing exception class names or SQL messages.
Key points
- ProblemDetail = RFC 9457
- @RestControllerAdvice centralizes mapping
- Stable types, no internals
Further reading: Spring MVC: Error responses
Go deeper: Spring Boot: Filters, DispatcherServlet and Interceptors in the Request Lifecycle course traces this step of the request, with a production bug and a runnable simulation.
Practice questions
What is RFC 9457?
Answer
The Problem Details for HTTP APIs standard (successor to RFC 7807), defining a JSON error format with type, title, status, detail and instance.
Why extend ResponseEntityExceptionHandler?
Answer
It already handles Spring MVC's built-in exceptions (validation, missing parameters, unsupported media types) as ProblemDetail responses, so you only add your domain mappings.
Open in the app to mark lessons complete, take notes and track your progress.