BackendBench
Coffee

Home โ€บ Java exceptions โ€บ MethodArgumentNotValidException

Checked exception ยท org.springframework.web.bind

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

How to fix it

  1. Read the field errors: e.getBindingResult().getFieldErrors() gives field, rejected value and message.
  2. Return a structured 400 body from an @ExceptionHandler or ResponseEntityExceptionHandler (or use Problem Details).
  3. Add @Valid on nested objects and elements of collections.
  4. Check JSON field names against the class if a field seems always empty.

Broken and fixed

fails
record CreateUser(String email) {}
// no constraints: bad data reaches the database
works
record 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.

Related exceptions

More tools you might need