Card 04/ 06
All 6 cards
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
@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {Read the field errors out of its BindingResult
Map<String, String> errors = new HashMap<>();
for (var error : ex.getBindingResult().getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}Return it with a 400
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}{"passengers":"Passengers must be at least 1","pickup":"Pickup location is required"}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.