Validation error responses tell users what went wrong when they send wrong or incomplete data. This helps users fix their input easily.
Validation error responses in Spring Boot
@RestController public class MyController { @PostMapping("/submit") public ResponseEntity<String> submitData(@Valid @RequestBody MyData data, BindingResult result) { if (result.hasErrors()) { // handle errors } return ResponseEntity.ok("Success"); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); } }
Use @Valid to trigger validation on input data.
Use @ExceptionHandler to catch validation errors and send a clear response.
@PostMapping("/user") public ResponseEntity<String> addUser(@Valid @RequestBody User user, BindingResult result) { if (result.hasErrors()) { return ResponseEntity.badRequest().body("Invalid user data"); } return ResponseEntity.ok("User added"); }
@ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleErrors(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); }
This Spring Boot controller accepts a user with a name. If the name is blank, it sends back a clear error message in JSON format.
import jakarta.validation.constraints.NotBlank; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import jakarta.validation.Valid; import java.util.HashMap; import java.util.Map; @RestController public class UserController { public static class User { @NotBlank(message = "Name must not be blank") public String name; } @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User created: " + user.name); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); for (FieldError error : ex.getBindingResult().getFieldErrors()) { errors.put(error.getField(), error.getDefaultMessage()); } return ResponseEntity.badRequest().body(errors); } }
Always add meaningful messages to your validation annotations for better feedback.
Use @ExceptionHandler to keep your controller methods clean and handle errors in one place.
Validation error responses help users fix their input by telling them what is wrong.
Use @Valid and @ExceptionHandler in Spring Boot to handle validation errors.
Return clear, field-specific messages in JSON for easy understanding.
Practice
Solution
Step 1: Understand validation error responses
Validation error responses are designed to tell users what input is wrong so they can correct it.Step 2: Identify the purpose in Spring Boot context
Spring Boot uses validation error responses to provide clear feedback to users, improving user experience.Final Answer:
To inform users about incorrect input so they can fix it -> Option BQuick Check:
Validation error responses = user input feedback [OK]
- Thinking validation errors speed up startup
- Assuming errors are only for developer logs
- Believing errors auto-correct input silently
Solution
Step 1: Identify annotation for validation
The@Validannotation tells Spring Boot to validate the object passed in the request.Step 2: Differentiate from other annotations
@RequestBody binds the request body, @Autowired injects dependencies, and @Controller marks a class as a controller, none trigger validation.Final Answer:
@Valid -> Option AQuick Check:
Validation trigger = @Valid [OK]
- Confusing @RequestBody with validation trigger
- Using @Autowired for validation incorrectly
- Thinking @Controller triggers validation
@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User created");
}Solution
Step 1: Understand validation failure behavior
When validation fails on a @Valid annotated object, Spring Boot returns a 400 Bad Request by default.Step 2: Check the method response
The method returns 200 OK only if validation passes; failure triggers automatic 400 response.Final Answer:
400 Bad Request -> Option AQuick Check:
Validation fail status = 400 Bad Request [OK]
- Assuming 200 OK even if validation fails
- Thinking validation failure causes 500 error
- Confusing 404 Not Found with validation errors
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleValidationError(MethodArgumentNotValidException ex) {
return ResponseEntity.badRequest().body(ex.getMessage());
}Solution
Step 1: Analyze the exception handler response
The handler returns only the exception message string, which is not user-friendly or field-specific.Step 2: Understand best practice for validation errors
Best practice is to return a JSON with detailed field error messages for clarity, not just a plain string.Final Answer:
It returns a plain message string instead of detailed field errors -> Option DQuick Check:
Validation error response should be detailed JSON [OK]
- Using wrong exception class (MethodArgumentNotValidException is correct)
- Returning HTTP 500 instead of 400
- Confusing @Valid usage with exception handling
Solution
Step 1: Understand how to customize validation error responses
Using a @ControllerAdvice with an @ExceptionHandler for MethodArgumentNotValidException allows extracting field errors and returning custom JSON.Step 2: Evaluate other options
Add @Valid to the controller method and rely on default error messages without customization uses default messages without customization; C uses wrong status; D returns plain string, not JSON.Final Answer:
Create a @ControllerAdvice class with @ExceptionHandler for MethodArgumentNotValidException that extracts field errors and returns a JSON map -> Option CQuick Check:
Custom JSON errors = @ControllerAdvice + @ExceptionHandler [OK]
- Relying on default messages without customization
- Using wrong HTTP status for validation errors
- Returning plain strings instead of JSON
Ready to prove it?
Pass the test and this pattern moves unknown
