Home โบ Java exceptions โบ MethodArgumentNotValidException
MethodArgumentNotValidException: causes and fixes
A @Valid request body failed Bean Validation: one or more constraints were violated.
What it looks like
org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] ... default message [must not be blank]Extends BindException in org.springframework.web.bind.
What it means
When a controller parameter is annotated with @Valid or @Validated, Spring validates it with Bean Validation (Hibernate Validator) before calling the method. Any violated constraint (@NotBlank, @Size, @Email, @Min) causes this exception, which maps to a 400 response. Its BindingResult lists every field error, so you can return all problems at once instead of one at a time.
Common causes
- A request missing a required field or with a blank string.
- A value outside the allowed range or pattern.
- Validation annotations placed on the wrong thing (a getter instead of the field, or missing
@Validon nested objects). - Mismatched JSON names that leave a field null.
How to fix it
- Read the field errors:
e.getBindingResult().getFieldErrors()gives field, rejected value and message. - Return a structured 400 body from an
@ExceptionHandlerorResponseEntityExceptionHandler(or use Problem Details). - Add
@Validon nested objects and elements of collections. - Check JSON field names against the class if a field seems always empty.
Broken and fixed
record CreateUser(String email) {}
// no constraints: bad data reaches the databaserecord CreateUser(@NotBlank @Email String email,
@Size(min = 8) String password) {}๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
For @RequestParam and @PathVariable constraints Spring 6.1 raises HandlerMethodValidationException instead.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is MethodArgumentNotValidException a checked or unchecked exception?
MethodArgumentNotValidException is a checked exception (it extends BindException), so the compiler forces you to catch it or declare it with throws.
Which package is MethodArgumentNotValidException in?
It lives in org.springframework.web.bind, so the import is import org.springframework.web.bind.MethodArgumentNotValidException;.
What is the first thing to check when I see MethodArgumentNotValidException?
Read the message and the first stack trace line in your own code. The usual causes are: A request missing a required field or with a blank string; and A value outside the allowed range or pattern.