Card 04/ 06

WalkthroughDifficulty: Advanced1 min

Turning Field Errors Into a Response

A bare 400 tells a client something was wrong. It doesn't say what. Catching the exception @Valid throws and reading its field errors turns that into something a client can actually act on.

From a failed validation to a field-by-field response

Step 1 of 3

Catch MethodArgumentNotValidException

java
@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {

Read the field errors out of its BindingResult

java
    Map<String, String> errors = new HashMap<>();
    for (var error : ex.getBindingResult().getFieldErrors()) {
        errors.put(error.getField(), error.getDefaultMessage());
    }

Return it with a 400

java
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
text
{"passengers":"Passengers must be at least 1","pickup":"Pickup location is required"}
run in a container — the real response body, built from the real field errors

Every message here came from the message attribute on the constraint annotations two cards back. A client reading this body knows exactly which two fields to fix, not just that something was wrong.