Scrivio Interview library
CodingIntermediate8 min read · updated 12 November 2026

Handle HandlerMethodValidationException from Spring 6.1 method validation and return field errors for parameters.

Since Spring Framework 6.1, Spring MVC validates constraint annotations placed directly on controller method parameters, and when they fail it throws HandlerMethodValidationException. We handle it by overriding handleHandlerMethodValidationException in a ResponseEntityExceptionHandler subclass, looping over getAllValidationResults() (one result per failing parameter, with the parameter and its errors), and, when we need different output for query parameters, path variables and request bodies, using the visitor that the exception provides.

Why this question is asked

Before Spring 6.1, a constraint such as @Min(1) on a @RequestParam did nothing unless we also put @Validated on the controller class, and then the failure arrived as a ConstraintViolationException that most applications turned into a 500. Spring 6.1 built method validation into Spring MVC itself, which is a real improvement, but it also introduced a new exception that many existing error handlers do not know about. Interviewers ask this to see whether we know which exception arrives when, and whether we can turn it into a useful 400 response. In this answer, we will recap when the exception is thrown, look at its structure, write a handler that returns field errors per parameter, refine it with the visitor API, and finish with the traps that make the handler never run.

1A Quick Recap of Method Validation in Spring MVC

Bean Validation is the Jakarta standard for declaring rules with annotations such as @NotBlank, @Min and @Size, and a validator (Hibernate Validator in a Spring Boot application with spring-boot-starter-validation) checks them. For years Spring MVC used it in one place only: a @RequestBody or @ModelAttribute argument marked @Valid. If that object broke a rule, Spring threw MethodArgumentNotValidException.

Spring 6.1 added built-in method validation. When a controller method has a constraint annotation directly on one of its parameters, for example @RequestParam @Max(100) int size, Spring MVC validates all the method's arguments before calling the method. If any rule fails, it throws HandlerMethodValidationException. Notice the difference: the rule sits on the parameter itself, not inside an object. Once method validation applies to a method, a @Valid @RequestBody on the same method is checked as part of the same step, and its errors are also reported in HandlerMethodValidationException rather than in MethodArgumentNotValidException.

Java
@RestController
class OrderController {
@GetMapping("/customers/{id}/orders")
List<OrderView> list(@PathVariable @Positive long id,
@RequestParam @Min(1) int page,
@RequestParam @Max(100) int size) {
return orders.find(id, page, size);
}
}
// GET /customers/7/orders?page=0&size=500
// -> HandlerMethodValidationException with 2 parameter results: page and size
// -> default response: 400 Bad Request, body without any field details

2What the Exception Contains

The exception is a MethodValidationResult, a container of results. getAllValidationResults() returns a list of ParameterValidationResult objects, one for each method parameter that has at least one error. Each result tells us which parameter failed through getMethodParameter(), which gives us the parameter name, its type and its annotations, and the value that was passed through getArgument().

The errors themselves come from getResolvableErrors(). Each one is a MessageSourceResolvable, Spring's general shape for a message: it has codes such as Max.size and Max, the constraint's arguments, and a default message such as must be less than or equal to 100. For a parameter that holds an object with fields, such as a @Valid @RequestBody, the result is a subclass called ParameterErrors, which also offers getFieldErrors() with the field name of each failure. In Spring 6.2 the same list is also available as getParameterValidationResults(); check your version for which name is preferred.

Which exception arrives for which rule
Where the rule isException in Spring 6.1+Default status
@Valid @RequestBody, no parameter constraintsMethodArgumentNotValidException400
@Min on a @RequestParam or @PathVariableHandlerMethodValidationException400
Both on the same methodHandlerMethodValidationException (body included)400
@Validated on the class (AOP validation)ConstraintViolationException500 unless handled
Constraint on the return valueHandlerMethodValidationException500
The same constraint can surface as three different exceptions, depending on where it is declared.

3Writing a Handler That Returns Field Errors

The cleanest place to handle it is a @RestControllerAdvice that extends ResponseEntityExceptionHandler. That base class already handles the standard Spring MVC exceptions and produces RFC 9457 problem details (a standard JSON error body with type, title, status and detail). It has a protected method for our exception, handleHandlerMethodValidationException, which by default returns a 400 problem with no field details. We override it and add a list of errors.

Java
@RestControllerAdvice
class ApiErrorHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHandlerMethodValidationException(
HandlerMethodValidationException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
List<Map<String, Object>> errors = new ArrayList<>();
for (ParameterValidationResult result : ex.getAllValidationResults()) {
String name = result.getMethodParameter().getParameterName(); // "size"
for (MessageSourceResolvable error : result.getResolvableErrors()) {
errors.add(Map.of(
"parameter", name,
"code", String.valueOf(error.getCodes()[error.getCodes().length - 1]), // "Max"
"message", String.valueOf(error.getDefaultMessage()))); // "must be less than or equal to 100"
}
}
ProblemDetail body = ProblemDetail.forStatusAndDetail(status, "Invalid request parameters");
body.setProperty("errors", errors);
return handleExceptionInternal(ex, body, headers, status, request);
}
}
// GET /customers/7/orders?page=0&size=500
// 400 {"type":"about:blank","title":"Bad Request","status":400,
// "detail":"Invalid request parameters","instance":"/customers/7/orders",
// "errors":[{"parameter":"page","code":"Min","message":"must be greater than or equal to 1"},
// {"parameter":"size","code":"Max","message":"must be less than or equal to 100"}]}

Notice that we pass the status we were given instead of hard-coding 400. The reason is that the same exception is also thrown when a constraint on the return value fails, and then Spring passes 500, because a bad return value is our bug, not the client's. We also call handleExceptionInternal at the end, so the base class still applies its usual steps, such as setting the instance field.

There is a catch with getParameterName(). Java only keeps parameter names in the class file when we compile with the -parameters flag. Spring Boot's Maven and Gradle plugins set it for us, and since Spring 6.1 Spring no longer falls back to reading debug information, so a project built another way can get null here. A name given in the annotation, such as @RequestParam("size"), is safer, and that is one reason for the visitor in the next section.

4Treating Each Kind of Parameter Differently With the Visitor

A flat list is fine for query parameters, but a request body is different: the client wants to know that items[2].quantity failed, not that the parameter called order failed. The exception offers visitResults(), which calls a different method of our Visitor for each kind of parameter: requestParam, pathVariable, requestHeader, cookieValue, matrixVariable, requestBody, requestPart, modelAttribute and other. Each method receives the annotation, so we can use the name declared there, and body methods receive ParameterErrors, so we can read the field errors.

Java
List<Map<String, String>> errors = new ArrayList<>();
ex.visitResults(new HandlerMethodValidationException.Visitor() {
public void requestParam(@Nullable RequestParam ann, ParameterValidationResult r) { add("query", r); }
public void pathVariable(PathVariable ann, ParameterValidationResult r) { add("path", r); }
public void requestHeader(RequestHeader ann, ParameterValidationResult r) { add("header", r); }
public void cookieValue(CookieValue ann, ParameterValidationResult r) { add("cookie", r); }
public void matrixVariable(MatrixVariable ann, ParameterValidationResult r) { add("path", r); }
public void requestPart(RequestPart ann, ParameterErrors e) { addFields("body", e); }
public void modelAttribute(@Nullable ModelAttribute ann, ParameterErrors e) { addFields("form", e); }
public void requestBody(RequestBody ann, ParameterErrors e) { addFields("body", e); }
public void other(ParameterValidationResult r) { add("other", r); }
private void add(String in, ParameterValidationResult r) {
String name = r.getMethodParameter().getParameterName();
r.getResolvableErrors().forEach(err ->
errors.add(Map.of("in", in, "name", name, "message", String.valueOf(err.getDefaultMessage()))));
}
private void addFields(String in, ParameterErrors e) {
e.getFieldErrors().forEach(fe ->
errors.add(Map.of("in", in, "name", fe.getField(), "message", String.valueOf(fe.getDefaultMessage()))));
}
});
// errors: [{"in":"query","name":"size",...}, {"in":"body","name":"items[2].quantity",...}]

Notice that the body errors now carry the field path from the object, while query errors carry the parameter name. The interface has one method per parameter kind, and newer versions add methods (for example, one for a validated list body), some with default implementations; check your version for which methods you must implement.

5Why the Handler Sometimes Never Runs

The most common trap is a leftover @Validated on the controller class. That annotation switches on Spring's older AOP method validation, a proxy that validates the call before it reaches the method. The proxy runs first, throws ConstraintViolationException, and our new handler never sees anything. The Spring documentation advises removing class-level @Validated from controllers once we rely on built-in method validation, so that the arguments are not validated twice by two mechanisms.

The second trap is a missing validator. Built-in method validation only applies when a Bean Validation provider is on the classpath. Without spring-boot-starter-validation, the constraints are silently ignored. A MockMvc test that sends page=0 and expects 400 with a parameter called page in the errors catches both traps at once.

Step throughWhat happens to GET /orders?page=0
  1. @Validated on the controller class?
    YesAOP proxy throws ConstraintViolationExceptionNoSpring MVC validates the arguments
  2. Constraint directly on a parameter?
    YesHandlerMethodValidationExceptionNoOnly @Valid bodies: MethodArgumentNotValidException
  3. ResponseEntityExceptionHandlercalls handleHandlerMethodValidationException
  4. Our overridebuilds the problem detail with errors

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Do I still need to handle MethodArgumentNotValidException?

Yes. A method that only has a @Valid @RequestBody, with no constraint annotations on its parameters, still reports failures with MethodArgumentNotValidException, because built-in method validation is not applied to it. Most real APIs have both kinds of methods, so a good error handler overrides both and produces the same error format from each, which keeps the contract the client sees identical.

Why does the default response not include the field errors?

Because Spring cannot know which details are safe and useful to expose. The default handler returns a 400 problem detail with a generic detail message. The errors are available on the exception, and it is up to us to decide how to present them, which is exactly what overriding handleHandlerMethodValidationException is for.

Where does the message text come from, and can I localize it?

The default message comes from the validator's message templates, such as must be less than or equal to {value}. Because each error is a MessageSourceResolvable, we can also resolve it through Spring's MessageSource with the request's locale and our own messages.properties, using the codes such as Max.size before falling back to the default message.

7Conclusion

In this answer, we saw that Spring MVC 6.1 validates constraints placed directly on controller parameters and throws HandlerMethodValidationException when they fail. The exception holds one ParameterValidationResult per failing parameter, each with the parameter and its resolvable errors, and getAllValidationResults() lets us turn them into a list of field errors. The visitor gives us a separate method per kind of parameter, so query parameters and request body fields can be reported differently. We override handleHandlerMethodValidationException in a ResponseEntityExceptionHandler subclass, keep the status Spring passes in, and remove class-level @Validated so the older AOP validation does not take over.

What to say in the interviewAbout 80 seconds aloud

Open with

Since Spring 6.1, if I put a constraint like @Min(1) directly on a @RequestParam or @PathVariable, Spring MVC validates the method arguments itself and throws HandlerMethodValidationException when something fails.

Then, if they want more

If the same method also has a @Valid request body, those errors are reported in the same exception. To return useful errors, I extend ResponseEntityExceptionHandler in a @RestControllerAdvice and override handleHandlerMethodValidationException. Inside, I loop over getAllValidationResults: each ParameterValidationResult gives me the method parameter, so I get its name, and getResolvableErrors gives me the codes and default messages.

I put those into a ProblemDetail as an errors property and return it with the status that was passed in, which is 400 for arguments and 500 when a return value fails validation.

If I want body fields reported with their paths, like items[2].quantity, and query parameters reported by name, I use visitResults with a Visitor, which has a method per annotation: requestParam, pathVariable, requestBody with ParameterErrors, and so on.

Two things I check: there is no leftover @Validated on the controller class, because then the AOP proxy throws ConstraintViolationException first, and the project compiles with -parameters so parameter names are available. And I lock it in with a MockMvc test that sends page=0.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Handle HandlerMethodValidationException from Spring 6.1 method validation and return...": https://scrivio-interview-library.netlify.app/spring-boot/error-handling/c94f8740da/