Bird
Raised Fist0
Spring Bootframework~20 mins

Validation error response formatting in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Validation Error Response Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Spring Boot validation error handler?
Given this controller advice method handling validation errors, what JSON response will it produce when a field "username" is empty?
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map handleValidationExceptions(MethodArgumentNotValidException ex) {
  Map errors = new HashMap<>();
  ex.getBindingResult().getAllErrors().forEach(error -> {
    String fieldName = ((FieldError) error).getField();
    String errorMessage = error.getDefaultMessage();
    errors.put(fieldName, errorMessage);
  });
  return errors;
}
A{"username": "must not be empty"}
B{"error": "Validation failed"}
C{"username": ""}
D{"message": "Field error"}
Attempts:
2 left
💡 Hint
Look at how the errors map is built from field names and messages.
📝 Syntax
intermediate
2:00remaining
Which option correctly formats a validation error response with a timestamp?
You want to include a timestamp and error details in your validation error response. Which code snippet correctly creates a JSON response with keys "timestamp" and "errors"?
A
Map&lt;String, Object&gt; body = new HashMap&lt;&gt;();
body.put("timestamp", LocalDateTime.now());
body.put("errors", errorsList);
return ResponseEntity.badRequest().body(body);
B
Map&lt;String, Object&gt; body = new HashMap&lt;&gt;();
body.put(timestamp, LocalDateTime.now());
body.put(errors, errorsList);
return ResponseEntity.badRequest().body(body);
C
Map&lt;String, String&gt; body = new HashMap&lt;&gt;();
body.put("timestamp", LocalDateTime.now().toString());
body.put("errors", errorsList.toString());
return ResponseEntity.ok().body(body);
D
Map body = new HashMap();
body.put("timestamp", LocalDateTime.now());
body.put("errors", errorsList);
return ResponseEntity.badRequest().body(body);
Attempts:
2 left
💡 Hint
Check for correct key quoting and response status.
🔧 Debug
advanced
2:00remaining
Why does this validation error handler cause a ClassCastException?
Consider this code snippet:
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map handleErrors(MethodArgumentNotValidException ex) {
  Map errors = new HashMap<>();
  for (Object error : ex.getBindingResult().getAllErrors()) {
    String field = ((FieldError) error).getField();
    String message = error.getDefaultMessage();
    errors.put(field, message);
  }
  return errors;
}

What is the most likely cause of a ClassCastException here?
AThe error.getDefaultMessage() returns null causing NullPointerException.
BThe map is declared with wrong generic types causing casting issues.
CSome errors in getAllErrors() are not FieldError instances, so casting fails.
DThe exception handler method lacks @ResponseStatus annotation causing runtime error.
Attempts:
2 left
💡 Hint
Not all errors are field errors in validation results.
state_output
advanced
2:00remaining
What is the JSON output of this custom validation error response?
Given this code snippet in a Spring Boot controller advice:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map handleValidationErrors(MethodArgumentNotValidException ex) {
  List errors = ex.getBindingResult().getFieldErrors().stream()
    .map(err -> err.getField() + ": " + err.getDefaultMessage())
    .toList();
  Map response = new HashMap<>();
  response.put("status", 400);
  response.put("errors", errors);
  return response;
}

What will the JSON response look like if the "email" field is invalid with message "must be a valid email"?
A{"status":400,"error":"email must be a valid email"}
B{"status":400,"errors":{"email":"must be a valid email"}}
C{"status":"400","errors":["email must be a valid email"]}
D{"status":400,"errors":["email: must be a valid email"]}
Attempts:
2 left
💡 Hint
Look at how errors list is built with field and message concatenated with colon.
🧠 Conceptual
expert
3:00remaining
Which approach best supports internationalized validation error responses in Spring Boot?
You want your validation error messages to appear in the user's language automatically. Which approach below best supports this in Spring Boot?
AHardcode error messages in English inside the exception handler and translate manually before sending response.
BUse MessageSource with locale resolver and call messageSource.getMessage() inside the exception handler to get localized messages.
CUse @ResponseStatus with fixed messages on exception classes without localization support.
DReturn raw default messages from validation annotations without any localization logic.
Attempts:
2 left
💡 Hint
Spring Boot supports message localization via MessageSource and locale resolvers.

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

  1. 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.
  2. Step 2: Identify the purpose of formatting

    Clear error messages improve user experience by showing which fields have issues and why.
  3. Final Answer:

    To provide clear error messages that help users understand input mistakes -> Option A
  4. 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

  1. Step 1: Identify global exception handling annotation

    @RestControllerAdvice is designed to handle exceptions across all controllers and format responses.
  2. 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.
  3. Final Answer:

    @RestControllerAdvice -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    A JSON object with field names as keys and error messages as values -> Option C
  4. 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

  1. 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.
  2. Step 2: Understand correct mapping

    Field names should be keys and error messages should be values for clarity in JSON response.
  3. Final Answer:

    The error message and field name are swapped when putting into the map -> Option B
  4. 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

Solution

  1. Step 1: Understand desired error response structure

    The response should have timestamp, status code, and detailed field errors in JSON format.
  2. 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.
  3. Step 3: Exclude incorrect options

    Returning plain strings or ModelAndView does not produce JSON with structured fields; throwing RuntimeException loses control over formatting.
  4. 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
  5. 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