Bird
0
0

To customize validation error responses in Spring Boot to return a JSON object listing each invalid field and its error message, which approach is most appropriate?

hard📝 Application Q8 of 15
Spring Boot - Exception Handling
To customize validation error responses in Spring Boot to return a JSON object listing each invalid field and its error message, which approach is most appropriate?
AImplement a @ControllerAdvice class with an @ExceptionHandler for MethodArgumentNotValidException that extracts field errors and builds a custom JSON response
BOverride the default error page in application.properties to display validation errors
CUse @ResponseStatus on the controller method to set a custom status code for validation errors
DAdd @JsonIgnore on all fields except those with validation errors
Step-by-Step Solution
Solution:
  1. Step 1: Identify customization point

    Validation errors throw MethodArgumentNotValidException which can be globally handled.
  2. Step 2: Use @ControllerAdvice and @ExceptionHandler

    Creating a global exception handler allows intercepting validation exceptions and customizing the response.
  3. Step 3: Extract field errors

    From the exception, extract field names and messages to build a structured JSON response.
  4. Final Answer:

    Implement a @ControllerAdvice class with an @ExceptionHandler for MethodArgumentNotValidException that extracts field errors and builds a custom JSON response correctly describes this approach.
  5. Quick Check:

    Use @ControllerAdvice with MethodArgumentNotValidException handler for custom JSON [OK]
Quick Trick: Use @ControllerAdvice and handle MethodArgumentNotValidException [OK]
Common Mistakes:
  • Trying to override error pages instead of exception handling
  • Using @ResponseStatus which only sets status, not response body
  • Misusing @JsonIgnore which affects serialization, not validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes