Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Validation error response formatting
📖 Scenario: You are building a Spring Boot REST API for user registration. You want to ensure that when users send invalid data, the API returns a clear, structured error response showing which fields failed validation and why.
🎯 Goal: Create a Spring Boot controller that validates a user registration request and returns a formatted JSON error response listing all validation errors with field names and messages.
📋 What You'll Learn
Create a User DTO with validation annotations
Add a controller method to accept User data
Configure a global exception handler to catch validation errors
Format the validation error response as JSON with field names and error messages
💡 Why This Matters
🌍 Real World
APIs often need to validate user input and return clear error messages so clients can fix mistakes easily.
💼 Career
Backend developers must handle validation and error formatting to build robust, user-friendly APIs.
Progress0 / 4 steps
1
Create User DTO with validation annotations
Create a class called User with two fields: String username and String email. Add validation annotations @NotBlank on username and @Email on email.
Spring Boot
Hint
Use @NotBlank on username and @Email on email fields.
2
Add controller method to accept User data
Create a Spring REST controller class called UserController. Add a method registerUser annotated with @PostMapping("/register") that accepts a @Valid @RequestBody User user parameter and returns ResponseEntity<String> with body "User registered".
Spring Boot
Hint
Use @RestController and @PostMapping("/register"). Add @Valid and @RequestBody to the User parameter.
3
Create global exception handler for validation errors
Create a class called GlobalExceptionHandler annotated with @RestControllerAdvice. Add a method handleValidationExceptions annotated with @ExceptionHandler(MethodArgumentNotValidException.class) that takes MethodArgumentNotValidException ex and returns a Map<String, String> mapping field names to error messages.
Spring Boot
Hint
Use @RestControllerAdvice and @ExceptionHandler to catch validation exceptions. Extract field errors and map field names to messages.
4
Return formatted JSON error response
Ensure the handleValidationExceptions method returns a Map<String, String> where keys are field names and values are validation error messages. This map will be serialized as JSON in the response.
Spring Boot
Hint
Return the map of errors directly so Spring Boot serializes it as JSON in the response.
Practice
(1/5)
1. What is the main purpose of formatting validation error responses in Spring Boot?
easy
A. To provide clear error messages that help users understand input mistakes
B. To speed up the application startup time
C. To reduce the size of the application package
D. To automatically fix invalid inputs
Solution
Step 1: Understand validation error responses
Validation errors occur when user input does not meet rules. Formatting these errors helps users know what went wrong.
Step 2: Identify the purpose of formatting
Clear error messages improve user experience by showing which fields have issues and why.
Final Answer:
To provide clear error messages that help users understand input mistakes -> Option A
Quick Check:
Validation error formatting = clear user messages [OK]
Hint: Errors should explain what and where input failed [OK]
Common Mistakes:
Thinking error formatting speeds startup
Assuming errors fix themselves automatically
Confusing error formatting with package size
2. Which annotation is used in Spring Boot to globally handle validation exceptions and format error responses?
easy
A. @RestControllerAdvice
B. @ComponentScan
C. @Service
D. @Controller
Solution
Step 1: Identify global exception handling annotation
@RestControllerAdvice is designed to handle exceptions across all controllers and format responses.
Step 2: Confirm other annotations are not for global error handling
@Controller is for MVC controllers, @Service for business logic, @ComponentScan for scanning components, none handle exceptions globally.
Final Answer:
@RestControllerAdvice -> Option A
Quick Check:
Global error handler = @RestControllerAdvice [OK]
Hint: Use @RestControllerAdvice for global error formatting [OK]
Common Mistakes:
Confusing @Controller with error handling
Using @Service or @ComponentScan incorrectly
Missing global exception handler annotation
3. Given this Spring Boot exception handler method, what will the JSON response contain when a validation error occurs?
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity> handleValidationErrors(MethodArgumentNotValidException ex) {
Map errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errors.put(error.getField(), error.getDefaultMessage());
});
return ResponseEntity.badRequest().body(errors);
}
medium
A. A plain text string listing all errors
B. An empty JSON object
C. A JSON object with field names as keys and error messages as values
D. A JSON array of error codes only
Solution
Step 1: Analyze the error map creation
The code collects field errors and puts each field name as key and its error message as value in a Map.
Step 2: Understand the response body
The Map is returned as JSON in the response body, so the client receives a JSON object with field-error pairs.
Final Answer:
A JSON object with field names as keys and error messages as values -> Option C
Quick Check:
Field-error map = JSON object with keys and messages [OK]
Hint: Map field to message for clear JSON error response [OK]
Common Mistakes:
Expecting plain text instead of JSON
Thinking response is empty or only codes
Confusing JSON array with JSON object
4. Identify the error in this Spring Boot validation error handler method:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity> handleErrors(MethodArgumentNotValidException ex) {
Map errors = new HashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.put(error.getDefaultMessage(), error.getField());
}
return ResponseEntity.badRequest().body(errors);
}
medium
A. The method does not handle the exception type correctly
B. The error message and field name are swapped when putting into the map
C. The response status should be OK instead of badRequest
D. The map should be a List instead
Solution
Step 1: Check map key-value assignment
The code uses error.getDefaultMessage() as key and error.getField() as value, which reverses the intended field-to-message mapping.
Step 2: Understand correct mapping
Field names should be keys and error messages should be values for clarity in JSON response.
Final Answer:
The error message and field name are swapped when putting into the map -> Option B
Quick Check:
Field as key, message as value is correct [OK]
Hint: Map field name as key, error message as value [OK]
Common Mistakes:
Swapping keys and values in error map
Using wrong exception class
Returning wrong HTTP status code
5. You want to customize your Spring Boot validation error response to include the timestamp, status code, and a list of field errors with messages. Which approach correctly implements this formatting?
hard
A. Throw a new RuntimeException inside the exception handler to trigger default error page
B. Return a plain string with all errors concatenated in the exception handler
C. Use @ControllerAdvice without @ResponseBody and return a ModelAndView for errors
D. Create a custom error response class with fields for timestamp, status, and a list of errors; populate it in a @RestControllerAdvice method handling MethodArgumentNotValidException
The response should have timestamp, status code, and detailed field errors in JSON format.
Step 2: Identify correct implementation method
Creating a custom error response class and populating it in a @RestControllerAdvice method allows structured JSON output with all required fields.
Step 3: Exclude incorrect options
Returning plain strings or ModelAndView does not produce JSON with structured fields; throwing RuntimeException loses control over formatting.
Final Answer:
Create a custom error response class with fields for timestamp, status, and a list of errors; populate it in a @RestControllerAdvice method handling MethodArgumentNotValidException -> Option D
Quick Check:
Custom class + @RestControllerAdvice = structured JSON error [OK]
Hint: Use custom class and @RestControllerAdvice for detailed JSON errors [OK]
Common Mistakes:
Returning plain text instead of JSON
Using @ControllerAdvice without JSON response
Throwing exceptions instead of formatting response