Sub topic 10
Reporting validation failures field by field
This chapter assumes you can build a basic REST controller and have read the chapters on @RestControllerAdvice and ProblemDetail. You also need spring-boot-starter-validation on the classpath. Without it, the @Valid annotation has no effect.
Where validation errors come from
Bean Validation checks a request body against constraint annotations such as @NotBlank and @Positive. When you put @Valid on a @RequestBody parameter, Spring validates the object after it deserializes the JSON. If any constraint fails, Spring throws MethodArgumentNotValidException before your controller method runs.
record CreateOrderRequest(@NotBlank String item, @Positive int quantity) {}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Order create(@Valid @RequestBody CreateOrderRequest request) {
return new Order(2L, request.item());
}Without a handler, the client gets a generic 400 response. It does not say which field was wrong. The exception object holds a BindingResult with one FieldError for every violated constraint, so you can report all of them in one response.
Building the field-level response
ResponseEntityExceptionHandler is a base class that already handles Spring MVC's own exceptions. Extend it in your advice and override handleMethodArgumentNotValid. This way validation errors use the same error format as everything else.
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.toList();
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return ResponseEntity.status(status).headers(headers).body(problem);
}This method sits inside the ApiExceptionHandler class from the previous chapter. A request with a blank item now produces this body:
{
"title": "Invalid request",
"status": 400,
"detail": "Validation failed",
"instance": "/orders",
"errors": ["item: must not be blank"]
}The errors entry is an extension member. RFC 9457 allows extra members on a problem detail, and setProperty adds them to the JSON.
Common mistakes
- Missing starter. The build compiles, but constraints are silently ignored. Add
spring-boot-starter-validation. - Constraints on the wrong thing. On a record, put annotations on the components, as shown above.
- Class-level errors.
getFieldErrors()skips errors that belong to the whole object, such as a cross-field constraint. ReadgetGlobalErrors()as well if you use those. - Leaking internals. Return
getDefaultMessage(), not the rejected value or the exception message. A rejected value can contain sensitive input.
Verifying the contract
Test the behavior with @WebMvcTest, which loads the controller and your advice without starting a server.
@Test
void blankItemReturnsFieldErrors() throws Exception {
mockMvc.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"item\":\"\",\"quantity\":1}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0]").value("item: must not be blank"));
}The test checks both the status code and the shape of the body. If someone changes the format later, it fails.
Exercise
A client sends {"item":"","quantity":0} to POST /orders. Which fields appear in the errors list, and why does the client get both errors in one response?
Show answer
Both item (must not be blank) and quantity (must be greater than 0) appear. Bean Validation checks every constraint before throwing, so the BindingResult holds one FieldError per violation, and the handler maps all of them into the errors list. The order of the entries is not guaranteed.