Sub topic 10
Reporting validation failures field by field
This chapter assumes you can build a Spring Boot REST controller, you know what a @RestControllerAdvice is, and you have seen ProblemDetail from the previous chapters. It covers how Bean Validation failures reach your code, how to turn them into a field-level error list, and the mistakes that most often break that.
Why validation errors need their own treatment
A request can be well-formed JSON and still be wrong. An empty item, or a quantity of -3, is a client mistake, so the answer is 400 Bad Request. A client needs more than "bad request" to fix it. It needs to know which field failed and why.
Without a handler, Spring Boot returns a generic 400. Its default /error body does not name the failing fields, and server.error.include-binding-errors=never hides them on purpose. You write the field-level report yourself, in the same ProblemDetail shape as your other errors.
Declaring constraints
Bean Validation is the standard Jakarta API for declaring rules as annotations. Spring Boot needs the spring-boot-starter-validation dependency, which pulls in Hibernate Validator as the implementation. Without it, the annotations are ignored. No error is raised and invalid data goes straight through.
Here is the controller and request type from this tutorial:
package com.example.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.util.Map;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
record Order(long id, String item) {}
record CreateOrderRequest(@NotBlank String item, @Positive int quantity) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final Map<Long, Order> orders = Map.of(1L, new Order(1L, "Book"));
@GetMapping("/{id}")
Order get(@PathVariable long id) {
return Optional.ofNullable(orders.get(id))
.orElseThrow(() -> new OrderNotFoundException(id));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Order create(@Valid @RequestBody CreateOrderRequest request) {
return new Order(2L, request.item());
}
}Two things trigger validation here. The constraint annotations sit on the record components, and @Valid sits on the @RequestBody parameter. If you leave out @Valid, nothing is checked.
What happens when validation fails
Spring MVC binds the JSON to CreateOrderRequest and then validates it. If any constraint fails, it throws MethodArgumentNotValidException before your controller method runs. That exception carries a BindingResult, which holds one FieldError for each failed field. Each FieldError has the field name, the rejected value, and a message.
The exception takes a different path through the resolver chain than your own exceptions. ResponseEntityExceptionHandler already knows how to handle it, so the right move is to extend that class and override one method.
Writing the handler
The global handler below extends ResponseEntityExceptionHandler and overrides handleMethodArgumentNotValid.
package com.example.orders;
import java.util.List;
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.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(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
@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);
}
@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 validation method does four things:
- It reads the field errors from the
BindingResult. - It formats each as
field: message. - It builds a 400
ProblemDetailand attaches the list as a custom property namederrors. - It returns a
ResponseEntityusing thestatusandheadersthat the base class passed in.
Posting {"item":"","quantity":-3} produces a body like this:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Validation failed",
"instance": "/orders",
"errors": [
"item: must not be blank",
"quantity: must be greater than 0"
]
}The order of the entries is not guaranteed. Hibernate Validator does not promise a stable order across fields, so clients must not depend on it. Sort the list in the handler if you need a fixed order, for example in tests.
Why override instead of adding an @ExceptionHandler
You could write @ExceptionHandler(MethodArgumentNotValidException.class) yourself. When the advice extends ResponseEntityExceptionHandler, that is a mistake. The base class already declares an @ExceptionHandler for this exception, and Spring then finds two mappings for the same type in one advice class. It fails with an "Ambiguous @ExceptionHandler method mapped" error. Override the protected method instead.
Overriding has a second benefit. The base class covers many other Spring MVC exceptions, such as unsupported media types and missing request parameters. Those all come out as ProblemDetail bodies as well. This is the same behaviour that spring.mvc.problemdetails.enabled=true gives you when you have no advice class.
Reporting richer errors
A list of strings is simple, but clients often want structure so they can put each message next to the right form field. Return objects instead:
record FieldViolation(String field, String message) {}Then map each FieldError to new FieldViolation(error.getField(), error.getDefaultMessage()) and set the list as the errors property. Jackson writes each record as {"field": "...", "message": "..."}. Pick one shape and keep it for every endpoint, because the point of this chapter is one consistent contract.
Class-level constraints, such as "end date must be after start date", produce a ObjectError and not a FieldError. getFieldErrors() skips them. If you use such constraints, also read getGlobalErrors() and add those to the list with a field name like "" or the object name.
Validating parameters, not only bodies
@Valid on a request body is one case. You can also put constraints directly on @PathVariable and @RequestParam parameters, for example @PathVariable @Positive long id. The exception depends on your Spring version:
| Spring Framework | Failing parameter constraint throws |
|---|---|
| 6.0 and earlier, with `@Validated` on the class | `ConstraintViolationException` |
| 6.1 and later, built-in method validation | `HandlerMethodValidationException` |
Spring Framework 6.1, used by Spring Boot 3.2 and later, validates controller method parameters itself when you have constraints on them. A failure raises HandlerMethodValidationException, which ResponseEntityExceptionHandler maps to 400. Override handleHandlerMethodValidationException to produce your field-level list for this case too. If you use @Validated on the class with an older version, you must write an @ExceptionHandler(ConstraintViolationException.class) yourself, and it is easy to forget. An unhandled ConstraintViolationException falls through to your catch-all handler and becomes a 500, which wrongly blames the server for a client mistake.
Common errors
- Missing starter. Constraints are silently ignored. Add
spring-boot-starter-validation. - Missing
@Valid. The body binds and the controller runs with invalid data. - Wrong exception for the wrong input. A body that is not valid JSON, or has a string where a number belongs, throws
HttpMessageNotReadableException. That is not a validation failure, so it does not reach your field list. The base class returns a 400 for it. - Primitive defaults hide missing fields. In
CreateOrderRequest, a missingquantitybecomes0becauseintcannot be null.@Positivethen rejects it, but with the message for0, not "required". UseIntegerwith@NotNullif you need to tell "missing" from "zero". - Exposing rejected values.
FieldError.getRejectedValue()returns what the client sent. Echoing it back can reflect sensitive input such as passwords, so leave it out of the response. - Message text as a contract.
getDefaultMessage()follows the server locale and the Hibernate Validator version. If clients parse messages, add a stable code and not the text. The constraint name fromerror.getCode(), such asNotBlank, works well for that.
Testing the field errors
A @WebMvcTest slice loads the controller and the @RestControllerAdvice without starting a server, so it checks both the status and the body.
package com.example.orders;
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.web.servlet.MockMvc;
@WebMvcTest(OrderController.class)
class OrderControllerErrorTest {
@Autowired
MockMvc mockMvc;
@Test
void unknownOrderReturnsProblemDetail() throws Exception {
mockMvc.perform(get("/orders/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Order not found"))
.andExpect(jsonPath("$.orderId").value(99));
}
@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 second test sends a valid quantity, so only one field fails. That keeps $.errors[0] stable. If you send two invalid fields, assert on the whole list with containsInAnyOrder because of the ordering note above.
Exercise
A client posts {"item":"Pen","quantity":0} to /orders. Which status code and which errors entry does the handler in this chapter return, and why does @Valid matter for this result?
Show answer
It returns 400 Bad Request with an errors list containing quantity: must be greater than 0. @Positive rejects 0. Without @Valid on the @RequestBody parameter, Spring would not run validation, the controller would run, and the response would be 201 Created.
Exercise
You add @PathVariable @Positive long id to a controller method on Spring Boot 3.3. Which exception does a request with id -5 raise, and what do you override in ResponseEntityExceptionHandler to format it as a field-level list?
Show answer
It raises HandlerMethodValidationException, because Spring Framework 6.1 and later validates method parameters itself. Override handleHandlerMethodValidationException and build the same ProblemDetail with an errors property there.