Sub topic 12
Returning consistent errors with @RestControllerAdvice
This chapter assumes you have the book API from the earlier chapters: the BookController, BookService, BookRequest with its @NotBlank annotations, and BookNotFoundException. You should also know what an HTTP status code is and how Java exceptions propagate. By the end, every failure the API can produce will return the same JSON shape, with no stack traces or HTML pages.
Why error handling needs one place
Without central handling, each failure looks different to a client:
- A missing book can produce Spring's default error page or JSON, depending on the request.
- A blank title produces a 400 response with a body in a different shape from the 404 body.
- An unexpected exception produces a 500 whose body may reveal internal details.
Clients then need special parsing for each case. Handling it in each controller method with try/catch is worse: it clutters the controller and the service has to know about HTTP.
The design here keeps the layers separate. The service throws a domain exception such as BookNotFoundException, which knows nothing about HTTP. One class translates exceptions into responses.
How Spring finds the handler
A controller method that throws does not send the exception to the client. Spring MVC's DispatcherServlet passes it to a chain of exception resolvers. One of them, ExceptionHandlerExceptionResolver, looks for a method annotated with @ExceptionHandler that matches the exception type. It checks the controller first, then every @ControllerAdvice or @RestControllerAdvice bean.
@RestControllerAdvice combines @ControllerAdvice and @ResponseBody. The returned objects are written to the response body, as they are for a @RestController. When several handlers match, the one whose declared exception type is closest to the thrown type wins.
The ProblemDetail format
RFC 7807 (updated by RFC 9457) defines a standard JSON shape for HTTP errors. Spring 6 provides it as ProblemDetail. The standard fields are:
| Field | Meaning |
|---|---|
| `type` | A URI identifying the kind of problem. Defaults to `about:blank`. |
| `title` | A short, human-readable summary of the problem type. |
| `status` | The HTTP status code. |
| `detail` | An explanation specific to this occurrence. |
| `instance` | A URI for this occurrence. Spring fills it with the request path. |
You can add custom fields with setProperty. The response content type is application/problem+json, so clients can recognize it.
The handler from the earlier chapter produces this for a missing book:
{
"type": "about:blank",
"title": "Book not found",
"status": 404,
"detail": "Book 42 not found",
"instance": "/api/books/42"
}What happens to validation errors
When @Valid fails on a @RequestBody, Spring throws MethodArgumentNotValidException before your controller method runs. If you do nothing, the client gets a 400 with little information about which field failed.
Spring provides a base class, ResponseEntityExceptionHandler. It already maps many framework exceptions to the right status codes, including malformed JSON, unsupported media types, unsupported methods, and type mismatches. Since Spring 6 it renders all of them as ProblemDetail. Extending it gives you consistent handling of these cases, and you override only the ones you want to customize.
Do not declare your own @ExceptionHandler for an exception the base class already handles. Spring fails at startup with an "Ambiguous @ExceptionHandler method" error. Override the base class method instead.
The complete handler
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(fieldError.getField(), fieldError.getDefaultMessage());
}
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return handleExceptionInternal(ex, problem, headers, status, request);
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal server error");
return problem;
}
}The three parts work as follows.
- Not found. This is the handler from the spine, unchanged. The service throws, and this method sets the 404 status and a title.
- Validation. The override collects one message per field into a map.
putIfAbsentkeeps the first message when a field has several violations.handleExceptionInternalis a base-class method that writes theProblemDetailwith the given status and headers. - Catch-all. Any exception without a more specific handler lands here. The full exception goes to the log, and the client sees a generic message. The base class handles framework exceptions with its own
@ExceptionHandler, which matches more closely thanException, so this method does not override them.
A blank title now produces a response like this:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Request validation failed",
"instance": "/api/books",
"errors": {
"title": "must not be blank"
}
}Choosing status codes
| Situation | Status | Source |
|---|---|---|
| Book id does not exist | 404 Not Found | `BookNotFoundException` handler |
| Field violates a constraint | 400 Bad Request | `MethodArgumentNotValidException` override |
| Body is not parseable JSON | 400 Bad Request | Base class |
| Path id is not a number, as in `/api/books/abc` | 400 Bad Request | Base class |
| Wrong HTTP method for the path | 405 Method Not Allowed | Base class |
| Unexpected failure | 500 Internal Server Error | Catch-all handler |
Use 404 for a missing resource and 400 for input that is wrong. The 500 status means a server fault, so do not use it for client mistakes.
Testing the error responses
The @WebMvcTest slice includes @RestControllerAdvice beans, so it exercises the real handler. The earlier test only checked the status codes. These tests also check the body.
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookErrorResponseTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private BookService service;
@Test
void notFoundReturnsProblemDetail() throws Exception {
when(service.get(7L)).thenThrow(new BookNotFoundException(7L));
mockMvc.perform(get("/api/books/7"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Book not found"))
.andExpect(jsonPath("$.detail").value("Book 7 not found"));
}
@Test
void blankTitleListsFieldErrors() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"author\":\"Ada\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.title").exists());
}
@Test
void unexpectedFailureHidesDetails() throws Exception {
when(service.get(9L)).thenThrow(new IllegalStateException("secret internal detail"));
mockMvc.perform(get("/api/books/9"))
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.detail").value("An unexpected error occurred"));
}
}@MockitoBean needs Spring Boot 3.4 or later. On older versions, use @MockBean from org.springframework.boot.test.mock.mockito. The third test checks the property that matters most for security: the exception's message must not appear in the response.
Common mistakes
- Handler never runs. The advice class is outside the package scanned from your
@SpringBootApplicationclass, or it lacks@RestControllerAdvice. - Startup fails with an ambiguous handler. You extended
ResponseEntityExceptionHandlerand also declared@ExceptionHandlerfor an exception it already handles. Override the protected method. - Two error shapes. You return a custom
ErrorResponseclass from one handler andProblemDetailfrom another. Pick one format and use it everywhere. - Exceptions swallowed. A
try/catchin the service that returnsnullor an empty result hides failures. Let exceptions propagate to the advice. - Exceptions from filters are not handled.
@RestControllerAdviceonly sees exceptions thrown from inside Spring MVC. A servlet filter, such as a security filter, throws earlier and needs its own handling.
Exercise
The service method delete(Long id) can also fail when the database rejects the delete, which throws a DataIntegrityViolationException. Which status code should the API return, which handler method signature would you add to ApiExceptionHandler, and why must you check that the base class does not already handle this exception?
Show answer
Return 409 Conflict, because the request is valid but conflicts with the current state of the data. Add a method such as @ExceptionHandler(DataIntegrityViolationException.class) public ProblemDetail handleConflict(DataIntegrityViolationException ex) that returns ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "The request conflicts with existing data") and logs the exception without exposing its message. ResponseEntityExceptionHandler only covers Spring MVC exceptions and not Spring Data exceptions, so no ambiguity arises. If it did cover the exception, a second @ExceptionHandler would fail at startup, and you would need to override the protected method instead.
Exercise
A client sends POST /api/books with the body {"title": "Dune", "author": } (invalid JSON). Which exception is thrown, which class handles it in the code above, and what status does the client get?
Show answer
Spring throws HttpMessageNotReadableException while reading the body, before validation runs. ResponseEntityExceptionHandler, the base class of ApiExceptionHandler, handles it, and the client receives a 400 Bad Request with a ProblemDetail body. The catch-all Exception handler does not take it, because the base class handler matches the exception type more closely.