Sub topic 12
Returning consistent errors with @RestControllerAdvice
This chapter assumes you have the book controller, service, and @Valid request validation from the earlier chapters. You should also know that Spring maps exceptions to HTTP responses.
Why centralize error handling
Without a handler, a missing book throws BookNotFoundException. Spring MVC treats it as an unhandled exception and returns a generic 500 response. Clients can't tell a server bug from a bad id. Validation failures return 400, but in a different shape from every other error.
A class annotated with @RestControllerAdvice fixes this. It applies to all controllers, and each @ExceptionHandler method in it converts one exception type into a response. The service keeps throwing plain Java exceptions and knows nothing about HTTP.
The error format: ProblemDetail
ProblemDetail is Spring's class for the RFC 7807 "problem details" format. It has the fields type, title, status, detail, and instance, and you can add custom properties. The response uses the content type application/problem+json.
A handler for not found and validation errors
The handler for BookNotFoundException was shown earlier. The version below keeps it and adds a handler for MethodArgumentNotValidException. Spring throws that exception when @Valid rejects a request body.
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(error -> errors.putIfAbsent(error.getField(), error.getDefaultMessage()));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return problem;
}
}putIfAbsent keeps the first message when one field breaks several constraints. A request with a blank title now returns this:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Request validation failed",
"instance": "/api/books",
"errors": { "title": "must not be blank" }
}Spring sets the HTTP status from the status field of the returned ProblemDetail, so you don't need @ResponseStatus here.
Common mistakes
- Catching
Exceptionbroadly. A handler forException.classalso swallows Spring's own exceptions, such as unsupported methods and malformed JSON, and turns them into your response. If you add a catch-all, make it return 500 and log the exception. Never putex.getMessage()in that response, because internal messages can leak details. - Putting HTTP knowledge in the service. Throw domain exceptions from the service. Choose status codes only in the advice class.
- Mixed formats. Spring Boot can also produce
ProblemDetailfor its own exceptions. Setspring.mvc.problemdetails.enabled=trueso framework errors, such as a malformed JSON body, use the same format as yours. - Inconsistent messages. Handlers return whatever you put in
detail. Keep the wording stable, because clients may display it.
Check it
The @WebMvcTest from the testing chapter already asserts the 404 and 400 statuses. You can also check that the body has the expected shape, for example with jsonPath("$.title").value("Book not found").
Exercise
A client sends PUT /api/books/42 for a book that does not exist, and the service throws BookNotFoundException. Which class turns that into a response, which status does the client receive, and why does the service not set the status itself?
Show answer
ApiExceptionHandler, through its @ExceptionHandler(BookNotFoundException.class) method, returns a ProblemDetail with status 404. The service only throws a domain exception. That keeps it free of HTTP concerns, so other callers can reuse it and only the advice class decides how errors map to status codes.