Fix MethodArgumentNotValidException and Return Clean Errors
Handle validation failures in Spring MVC by turning MethodArgumentNotValidException and HandlerMethodValidationException into one clear error response.

The default response to an invalid request body is a 400 whose JSON describes the exception and not the problem. The server log prints something like this:
org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public ... OrderView create(CreateOrder): [Field error in object 'createOrder' on field 'customerId': rejected value []; codes [NotBlank...]; default message [must not be blank]]A client cannot use that, and a user cannot be shown it. This guide turns validation failures into a response a client can act on, in four steps: declare the rules on the request type, handle the exception once, handle the related exception for parameters and cover the global errors that field-based handling misses. It targets Spring Framework 7 on Spring Boot 4. The surrounding API design is in building REST APIs with Spring MVC.
Declare the rules on the request type
public record CreateOrder(
@NotBlank String customerId,
@NotEmpty List<@Valid Line> lines) {
public record Line(@NotBlank String sku, @Positive int quantity) {}
}The nested @Valid is what makes validation reach the elements of the list. Without it, a line with a negative quantity passes, and no message says why. Constraints go on the record's components, so the rules sit next to the data, and a record keeps the request type immutable. Then ask Spring to validate the body.
@PostMapping
ResponseEntity<OrderView> create(@Valid @RequestBody CreateOrder request) {
// the body is valid here
}Spring validates before the method runs, so the method body never sees an invalid object, and can assume the rules hold.
Handle it once
@RestControllerAdvice
class ValidationAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalidBody(MethodArgumentNotValidException e) {
ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
p.setTitle("Validation failed");
p.setProperty("errors", e.getBindingResult().getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "message", String.valueOf(f.getDefaultMessage())))
.toList());
return p;
}
}A request with an empty customerId and a line with quantity 0 now receives:
{
"title": "Validation failed",
"status": 400,
"errors": [
{"field": "customerId", "message": "must not be blank"},
{"field": "lines[0].quantity", "message": "must be greater than 0"}
]
}The field path lines[0].quantity tells the client exactly which element failed, so a form can put the message next to the right input. The order of the errors may vary between runs, so clients should not depend on it. The response uses the standard problem format, which the project can apply to every error; its design is covered in designing error responses. Never include the rejected value in the response for sensitive fields such as passwords.
Parameters and path variables
Constraints on simple parameters take a different route.
@GetMapping("/orders")
List<OrderView> list(@RequestParam @Min(1) @Max(100) int size) { /* ... */ }Before Spring Framework 6.1 this needed @Validated on the controller class and threw ConstraintViolationException. From 6.1, built-in method validation applies when the method has constraint annotations, and the exception is HandlerMethodValidationException. Handle it as well:
@ExceptionHandler(HandlerMethodValidationException.class)
ProblemDetail invalidParameter(HandlerMethodValidationException e) {
ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
p.setTitle("Validation failed");
p.setDetail("One or more request parameters are invalid.");
return p;
}Putting @Validated on the class in 6.1 and later switches back to the older AOP-based approach and its exception type, so do not mix the two without meaning to. If a parameter constraint seems ignored, check which of the two paths the method is on.
Global errors
A class-level constraint, such as "the end date must be after the start date", reports through getBindingResult().getGlobalErrors() and not through field errors. Include both lists in your response, or those rules appear to pass silently while the client receives a 400 with an empty errors array. A simple way is to map global errors with an empty or fixed field, such as "*", so clients can display them at the top of a form.
Customise the messages
Messages come from the constraint's message attribute or from ValidationMessages.properties. Keep them user-facing and specific.
@NotBlank(message = "customerId is required")
String customerIdFor translated messages, resolve them through the request's locale with a MessageSource, using the constraint's message key. Test one invalid request per rule and assert on the field and the message, because a message that changes silently is an API change.
Testing the handler
mockMvc.perform(post("/orders").contentType(APPLICATION_JSON).content("{\"customerId\":\"\",\"lines\":[]}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[?(@.field=='customerId')].message").value("must not be blank"));This one test proves the annotation, the advice and the response shape together.
Keeping messages consistent across endpoints
The most common drift is one endpoint returning errors as a list of objects and another as a map. Fix the shape once, in a shared helper that converts a binding result into the response, and call it from every handler. Document the shape in your API description and keep one contract test for it. Clients that build form error displays against this format then work for every endpoint without special cases.
Logging validation failures
Validation errors are client mistakes, so log them at debug or info level without a stack trace. A high rate of one specific rule failing is a signal worth watching: it often means the documentation or the client form is wrong, not the users. Count failures by field name as a metric, and the dashboard shows which rule confuses people.
Validation groups and conditional rules
One request type sometimes serves a create and an update, with different rules: an id is forbidden on create and required on update. Bean Validation groups express that. Declare marker interfaces OnCreate and OnUpdate, put groups = OnCreate.class on the constraints that differ, and select the group with @Validated(OnCreate.class) on the parameter. Groups add ceremony, so a simpler option is two request records, CreateOrder and UpdateOrder, each with exactly the fields that operation accepts. Separate types also make the API documentation honest, since each operation lists only its own fields.
Custom constraints
When no standard annotation fits, write one: a @ValidSku annotation with a ConstraintValidator that checks the format or looks up a catalogue. Keep validators free of side effects and avoid database calls in them where you can, because they run on every request and a slow lookup becomes a slow endpoint. Rules that need data, such as "this email is not already registered", belong in the service layer, where a conflict can be reported with a 409 and a clear type, since a race between two requests makes any pre-check unreliable anyway.
Limiting the size of the error list
A request with ten thousand invalid list elements produces ten thousand errors, and the response grows with it. Cap the list in the handler at a sensible number, say fifty, and add a flag or a count so the client knows that more exist.
Where this handler does not apply
Binding errors for data that cannot be parsed at all, such as text in a number field, arrive earlier as [HttpMessageNotReadableException](/library/httpmessagenotreadableexception-fix-json-parse-error). Validation of values after binding is Bean Validation's job, documented in the Spring validation reference. Spring Boot's spring.mvc.problemdetails.enabled property extends problem responses to the framework's own exceptions. For other request-binding errors a controller can raise, see [MissingServletRequestParameterException](/library/missingservletrequestparameterexception-fix-spring-mvc). The Spring MVC reference documents the behaviour in detail.


