Skip to lesson

Validation error responses with field details

A shopper submits the product form with a bad SKU, a one-letter name and a negative price. Should the API report only the first problem, or tell the app about all three at once?

MethodArgumentNotValidException as a list of field errors

MethodArgumentNotValidException is what Spring MVC throws when a @Valid @RequestBody object breaks its Bean Validation rules. It carries a BindingResult with one FieldError per broken rule, each with the field name and your message.

A handler turns each FieldError into an InvalidField(field, message) and returns them in one errors list.

Example 1 · ApiError, InvalidField, InvalidFields and the body handler

Runs in: the errors-lab practice project (Spring Boot 4.1)

ApiError.javaJava
// src/main/java/com/shoplite/lab/common/ApiError.javapackage com.shoplite.lab.common;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
/** Temporary error body for this lab. The ProblemDetail lesson replaces it with the standard one. */public record ApiError(int status, String title, String detail, String instance,                       @JsonInclude(JsonInclude.Include.NON_EMPTY) List<InvalidField> errors) {
    public ApiError(int status, String title, String detail, String instance) {        this(status, title, detail, instance, List.of());    }}
// src/main/java/com/shoplite/lab/common/InvalidField.javapackage com.shoplite.lab.common;
/** One broken input: the field (or parameter) name and what is wrong with it. */public record InvalidField(String field, String message) {}
// src/main/java/com/shoplite/lab/common/InvalidFields.javapackage com.shoplite.lab.common;
import java.lang.reflect.RecordComponent;import java.util.Arrays;import java.util.Comparator;import java.util.List;
import org.springframework.validation.Errors;
/** Turns Spring's field errors into InvalidField items, in the order the record declares its fields. */final class InvalidFields {
    private InvalidFields() {    }
    static List<InvalidField> of(Errors errors, Object target) {        List<String> declared = declaredNames(target);        return errors.getFieldErrors().stream()                .map(e -> new InvalidField(e.getField(), e.getDefaultMessage()))                .sorted(Comparator.comparingInt((InvalidField f) -> position(declared, f.field()))                        .thenComparing(InvalidField::field)                        .thenComparing(InvalidField::message))                .toList();    }
    private static List<String> declaredNames(Object target) {        if (target == null || !target.getClass().isRecord()) {            return List.of();        }        return Arrays.stream(target.getClass().getRecordComponents()).map(RecordComponent::getName).toList();    }
    private static int position(List<String> declared, String field) {        String topLevel = field.split("[.\\[]", 2)[0];        int index = declared.indexOf(topLevel);        return index >= 0 ? index : declared.size();    }}
@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<ApiError> handleInvalidBody(MethodArgumentNotValidException ex,                                                  HttpServletRequest request) {    List<InvalidField> errors = InvalidFields.of(ex.getBindingResult(), ex.getBindingResult().getTarget());    return validationFailed(errors, request);}
private ResponseEntity<ApiError> validationFailed(List<InvalidField> errors, HttpServletRequest request) {    long fields = errors.stream().map(InvalidField::field).distinct().count();    String detail = "The request has " + fields + (fields == 1 ? " invalid field." : " invalid fields.");    ApiError body = new ApiError(400, "Validation failed", detail, request.getRequestURI(), errors);    return ResponseEntity.badRequest().body(body);}
Output
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
{"status":400,"title":"Validation failed","detail":"The request has 3 invalid fields.","instance":"/api/v1/products","errors":[{"field":"sku","message":"must be 3-20 characters: A-Z, 0-9 or -"},{"field":"name","message":"must be 2-120 characters"},{"field":"price","message":"must be greater than 0"}]}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
{"status":400,"title":"Validation failed","detail":"The request has 1 invalid field.","instance":"/api/v1/products","errors":[{"field":"sku","message":"is required"}]}

What this code does

  • All three broken fields come back in one reply, in the order of the record: sku, name, price. The detail counts them, with "field" or "fields" as needed.
  • A missing sku shows the @NotNull(message = "is required") text. The messages are the ones written on CreateProductRequest, so clients see your wording, not Hibernate Validator's defaults.
  • InvalidFields reads the record's components with getRecordComponents() to sort; "items[0].quantity" is sorted by its top-level name items.

The last lesson's catch-all turned this exception into a vague 400 Bad Request with the detail Invalid request content. A client cannot show a user which box to fix from that.

Validators report errors in no fixed order, so InvalidFields sorts them in the order the request record declares its fields, which matches the order of the JSON body in the ShopLite contract.

HandlerMethodValidationException for parameter errors

HandlerMethodValidationException is what Spring MVC 6.1 and later throw when constraints written directly on controller parameters fail, such as @Positive long id or @Max(100) int size. Spring checks them before your method runs.

A controller with constraints on its query and path parameters, and the handler that turns the exception into the same errors list.

Example 2 · Parameter constraints and the HandlerMethodValidationException handler

Runs in: the errors-lab practice project (Spring Boot 4.1)

ProductController.javaJava
// src/main/java/com/shoplite/lab/product/ProductController.javapackage com.shoplite.lab.product;
import java.util.List;
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.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.Pattern;import jakarta.validation.constraints.Positive;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
    private final ProductService productService;
    public ProductController(ProductService productService) {        this.productService = productService;    }
    @GetMapping    public List<ProductResponse> list(            @RequestParam(defaultValue = "0") @Min(value = 0, message = "must be 0 or more") int page,            @RequestParam(defaultValue = "20")            @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size,            @RequestParam(defaultValue = "id")            @Pattern(regexp = "(id|name|price|stock)(,(asc|desc))?",                     message = "must be one of id, name, price, stock") String sort) {        return productService.list(page, size);    }
    @GetMapping("/{id}")    public ProductResponse getProduct(@PathVariable @Positive(message = "must be greater than 0") long id) {        return productService.findById(id);    }
    @GetMapping("/average-price")    public AveragePriceResponse averagePrice(@RequestParam long categoryId) {        return new AveragePriceResponse(categoryId, productService.averagePrice(categoryId));    }
    @PostMapping    @ResponseStatus(HttpStatus.CREATED)    public ProductResponse create(@Valid @RequestBody CreateProductRequest request) {        return productService.create(request);    }
    @PutMapping("/{id}")    public ProductResponse replace(@PathVariable @Positive(message = "must be greater than 0") long id,                                   @Valid @RequestBody CreateProductRequest request) {        return productService.replace(id, request);    }}
// src/main/java/com/shoplite/lab/common/GlobalExceptionHandler.java (new handler)@ExceptionHandler(HandlerMethodValidationException.class)public ResponseEntity<ApiError> handleInvalidParameters(HandlerMethodValidationException ex,                                                        HttpServletRequest request) {    List<InvalidField> errors = new ArrayList<>();    for (ParameterValidationResult result : ex.getParameterValidationResults()) {        if (result instanceof ParameterErrors bodyErrors) {            errors.addAll(InvalidFields.of(bodyErrors, bodyErrors.getArgument()));        } else {            String name = result.getMethodParameter().getParameterName();            for (MessageSourceResolvable error : result.getResolvableErrors()) {                errors.add(new InvalidField(name, error.getDefaultMessage()));            }        }    }    return validationFailed(errors, request);}
Output
$ curl "http://localhost:8080/api/v1/products?size=500&sort=password"
{"status":400,"title":"Validation failed","detail":"The request has 2 invalid fields.","instance":"/api/v1/products","errors":[{"field":"size","message":"must be between 1 and 100"},{"field":"sort","message":"must be one of id, name, price, stock"}]}
$ curl "http://localhost:8080/api/v1/products?page=-1&size=0"
{"status":400,"title":"Validation failed","detail":"The request has 2 invalid fields.","instance":"/api/v1/products","errors":[{"field":"page","message":"must be 0 or more"},{"field":"size","message":"must be between 1 and 100"}]}
$ curl http://localhost:8080/api/v1/products/0
{"status":400,"title":"Validation failed","detail":"The request has 1 invalid field.","instance":"/api/v1/products/0","errors":[{"field":"id","message":"must be greater than 0"}]}
$ curl -X PUT http://localhost:8080/api/v1/products/0 -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
{"status":400,"title":"Validation failed","detail":"The request has 4 invalid fields.","instance":"/api/v1/products/0","errors":[{"field":"id","message":"must be greater than 0"},{"field":"sku","message":"must be 3-20 characters: A-Z, 0-9 or -"},{"field":"name","message":"must be 2-120 characters"},{"field":"price","message":"must be greater than 0"}]}

What this code does

  • Both bad query parameters are reported together, with the names size and sort and the messages from the annotations.
  • The last call breaks the path variable and three body fields at once. Because replace has a constraint on id, Spring validated everything in one go and sent the body errors as ParameterErrors; the handler unpacks them with InvalidFields.of.
  • Without the ParameterErrors branch, PUT with a bad body would lose its field list while POST kept it.

Each ParameterValidationResult belongs to one parameter: its MethodParameter gives the name (size, sort) and its errors give the messages. So the same errors list works for query and path parameters.

One surprise: once a method has a constraint on any parameter, its @Valid @RequestBody is checked by method validation too. The body errors then arrive inside this exception as ParameterErrors, not as MethodArgumentNotValidException. The handler must unpack both, or PUT /products/{id} reports bodies differently from POST.

Parameter names come from the compiled class. The Spring Boot Maven parent compiles with -parameters, so size stays size; without it Spring cannot know the names.

Malformed JSON and wrong types

HttpMessageNotReadableException means Jackson could not turn the request body into your request object at all: the JSON is broken, a value has the wrong type, a field is unknown or the body is missing. Validation never runs.

Handlers for an unreadable body and for a parameter of the wrong type, then six bad requests to try.

Example 3 · Unreadable bodies and parameters of the wrong type

Runs in: the errors-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/common/GlobalExceptionHandler.java (new handlers and helpers)@ExceptionHandler(MethodArgumentTypeMismatchException.class)public ResponseEntity<ApiError> handleTypeMismatch(MethodArgumentTypeMismatchException ex,                                                   HttpServletRequest request) {    Class<?> type = ex.getRequiredType();    boolean number = type != null && (Number.class.isAssignableFrom(type)            || type == int.class || type == long.class || type == double.class);    String message = number ? "must be a number" : "has an invalid value";    return validationFailed(List.of(new InvalidField(ex.getName(), message)), request);}
@ExceptionHandler(HttpMessageNotReadableException.class)public ResponseEntity<ApiError> handleUnreadableBody(HttpMessageNotReadableException ex,                                                     HttpServletRequest request) {    return error(HttpStatus.BAD_REQUEST, "Malformed request", describe(ex), request);}
private static String describe(HttpMessageNotReadableException ex) {    Throwable cause = ex.getCause();    if (cause instanceof UnrecognizedPropertyException unknown) {        return "Unknown field " + path(unknown) + ".";    }    if (cause instanceof MismatchedInputException wrongType && !wrongType.getPath().isEmpty()) {        return "Field " + path(wrongType) + " has the wrong type.";    }    if (cause == null) {        return "The request body is missing.";    }    return "The request body is not valid JSON.";}
private static String path(JacksonException ex) {    StringBuilder path = new StringBuilder();    for (JacksonException.Reference ref : ex.getPath()) {        if (ref.getPropertyName() != null) {            path.append(path.isEmpty() ? "" : ".").append(ref.getPropertyName());        } else {            path.append('[').append(ref.getIndex()).append(']');        }    }    return path.toString();}
Output
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30,}'
{"status":400,"title":"Malformed request","detail":"The request body is not valid JSON.","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB101","name":"Zebronics Wireless Keyboard","categoryId":4,"price":"abc","stock":30}'
{"status":400,"title":"Malformed request","detail":"Field price has the wrong type.","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"id":5,"sku":"ACC-KB102","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
{"status":400,"title":"Malformed request","detail":"Unknown field id.","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json"
{"status":400,"title":"Malformed request","detail":"The request body is missing.","instance":"/api/v1/products"}
$ curl "http://localhost:8080/api/v1/products?size=abc"
{"status":400,"title":"Validation failed","detail":"The request has 1 invalid field.","instance":"/api/v1/products","errors":[{"field":"size","message":"must be a number"}]}
$ curl http://localhost:8080/api/v1/products/abc
{"status":400,"title":"Validation failed","detail":"The request has 1 invalid field.","instance":"/api/v1/products/abc","errors":[{"field":"id","message":"must be a number"}]}

What this code does

  • Jackson's exception, ex.getCause(), tells the cases apart: UnrecognizedPropertyException for id, MismatchedInputException with a path for "abc", no cause at all for a missing body. Spring Boot 4 uses Jackson 3, whose classes live in the tools.jackson packages.
  • None of these replies shows Java class names or Jackson's own message, which contains internal details; the describe method writes a safe sentence instead.
  • size=abc and /products/abc are parameters, so the contract makes them validation-failed with an errors item, not malformed-request.

MethodArgumentTypeMismatchException is the same idea for a path or query parameter, such as size=abc or /products/abc. Without handlers, the unreadable body fell into the catch-all as a 500 and was logged as a bug, though the client caused it, and the bad parameter also gave 500.

The ShopLite contract calls a body Jackson cannot read malformed-request, and a parameter with a bad value validation-failed. Jackson's exception (the cause) tells which case it is, and its path gives the field name. Unknown fields are rejected only after spring.jackson.deserialization.fail-on-unknown-properties=true; by default Jackson ignores them.

Predict the output

Which exception does Spring throw?

Pick the exception for each bad request.

Round 1 of 3

POST a product whose body has "price": "abc".

@PostMapping
public ProductResponse create(@Valid @RequestBody CreateProductRequest request) { ... }
// body: {"sku":"ACC-KB101","name":"Keyboard","price":"abc"}

One errors array shape for every kind of bad input

The same four requests against the lab as it was before these handlers: vague answers, and one 500.

Example 4 · Before these handlers: three answers for bad input

Runs in: the errors-lab practice project (Spring Boot 4.1)

Terminal
curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'curl "http://localhost:8080/api/v1/products?size=500&sort=password"curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100",}'curl -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
Output
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
{"status":400,"title":"Bad Request","detail":"Invalid request content.","instance":"/api/v1/products"}
$ curl "http://localhost:8080/api/v1/products?size=500&sort=password"
{"status":400,"title":"Bad Request","detail":"Validation failure","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100",}'
{"status":500,"title":"Internal server error","detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products"}
$ curl -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
{"status":400,"title":"Bad Request","detail":"Validation failure","instance":"/api/v1/products/6"}

What this code does

  • This is the same lab with only the previous lesson's handlers. Two bodies say almost nothing, and the broken JSON became a 500 that was logged as a bug.
  • After this lesson the same four requests give two clear shapes: Validation failed with errors (Examples 1 and 2) and Malformed request (Example 3).

Every kind of bad input now ends in one of two answers, always with status 400. A body that cannot be read gives Malformed request with a one-line detail. Values that break rules give Validation failed with an errors array of {field, message} items. The exception decides which:

  • MethodArgumentNotValidException (a @Valid body) → Validation failed, errors from the BindingResult.
  • HandlerMethodValidationException (parameters, or a body on a method with parameter constraints) → Validation failed.
  • MethodArgumentTypeMismatchException (size=abc, /products/abc) → Validation failed, message must be a number.
  • HttpMessageNotReadableException (broken JSON, wrong type, unknown field, no body) → Malformed request.
The errors field appears only when it has items, thanks to @JsonInclude(NON_EMPTY) on the record component. Other errors keep the four plain fields.

Showing several field errors at once

A field error names one broken field and says what is wrong with it, such as price: must be greater than 0. A good API reports every field error it finds in one reply, not just the first.

A nested order: every broken item row is reported together, with its index in the field name.

Example 5 · Nested order items: every broken row at once

Runs in: the errors-lab practice project (Spring Boot 4.1)

PlaceOrderRequest.javaJava
// src/main/java/com/shoplite/lab/order/PlaceOrderRequest.javapackage com.shoplite.lab.order;
import java.util.List;
import jakarta.validation.Valid;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Size;
public record PlaceOrderRequest(        @NotNull(message = "is required") Long customerId,        @NotNull(message = "is required") Long addressId,        @NotNull(message = "is required")        @Size(min = 1, max = 20, message = "must have 1-20 items")        List<@Valid OrderItemRequest> items) {}
// src/main/java/com/shoplite/lab/order/OrderItemRequest.javapackage com.shoplite.lab.order;
import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.NotNull;
public record OrderItemRequest(        @NotNull(message = "is required") Long productId,        @NotNull(message = "is required")        @Min(value = 1, message = "must be between 1 and 10")        @Max(value = 10, message = "must be between 1 and 10") Integer quantity) {}
Output
$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":1},{"productId":6,"quantity":12},{"quantity":0}]}'
{"status":400,"title":"Validation failed","detail":"The request has 3 invalid fields.","instance":"/api/v1/orders","errors":[{"field":"items[1].quantity","message":"must be between 1 and 10"},{"field":"items[2].productId","message":"is required"},{"field":"items[2].quantity","message":"must be between 1 and 10"}]}
$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"items":[]}'
{"status":400,"title":"Validation failed","detail":"The request has 2 invalid fields.","instance":"/api/v1/orders","errors":[{"field":"addressId","message":"is required"},{"field":"items","message":"must have 1-20 items"}]}
$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":"two"}]}'
{"status":400,"title":"Malformed request","detail":"Field items[0].quantity has the wrong type.","instance":"/api/v1/orders"}

What this code does

  • List<@Valid OrderItemRequest> makes Bean Validation check every item, and the field paths carry the index: the second item has a bad quantity, the third has two problems.
  • An empty list breaks @Size(min = 1) and a missing addressId breaks @NotNull; both are reported together.
  • "quantity": "two" cannot even be read, so it is a malformed request, and Jackson's path still points to items[0].quantity.

Bean Validation already checks every constraint on every field, so the handler only has to keep them all. The alternative is a guessing game: the client fixes sku, sends again, learns about name, sends again, learns about price. On a phone with a slow network that is three round trips and three annoyed users.

For nested objects the field names carry the index, such as items[1].quantity, so the app can mark the exact row of the cart. The detail counts fields, not messages: items[2].productId and items[2].quantity are two different fields.

Next step

Check your understanding

12 quick questions