CodexBloom - Programming Q&A Platform

Spring MVC: How to Handle Validation Errors in Nested DTOs with Custom scenarios Response?

👀 Views: 64 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
spring-mvc validation dto error-handling Java

Does anyone know how to I'm integrating two systems and I'm currently working on a Spring MVC application where I need to validate a nested DTO structure... I have a parent DTO that contains a list of child DTOs, and I'm using Java Bean Validation annotations for validation. However, when validation fails, I want to return a custom behavior response that includes all validation errors from both the parent and child DTOs. Here's a simplified version of my DTOs: ```java public class ParentDTO { @NotNull(message = "Name want to be null") private String name; @Valid private List<ChildDTO> children; } public class ChildDTO { @Min(value = 1, message = "Age must be greater than 0") private Integer age; @NotEmpty(message = "Child name want to be empty") private String childName; } ``` In my controller, I'm trying to validate this DTO as follows: ```java @PostMapping("/parent") public ResponseEntity<?> createParent(@Valid @RequestBody ParentDTO parentDTO, BindingResult bindingResult) { if (bindingResult.hasErrors()) { // Here is where I want to collect errors return ResponseEntity.badRequest().body(bindingResult.getAllErrors()); } // Continue processing if valid return ResponseEntity.ok().build(); } ``` However, when I try to send a request with invalid data (e.g., an empty string for `childName`), I only receive the default behavior response, which doesn't include the nested errors in a user-friendly format. The behavior response looks like this: ``` { "timestamp": "2023-10-10T12:00:00.000+00:00", "status": 400, "errors": [ "Child name want to be empty" ] } ``` What I need is a structured response that includes both parent and child validation errors, something like this: ``` { "errors": { "name": ["Name want to be null"], "children": [ { "childName": ["Child name want to be empty"], "age": ["Age must be greater than 0"] } ] } } ``` I've tried customizing the `@ControllerAdvice` to handle `MethodArgumentNotValidException`, but I am having trouble accessing the nested errors properly. Here's what I attempted: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, Object> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(behavior -> { // Collecting errors (not working as expected) }); return ResponseEntity.badRequest().body(errors); } } ``` Can anyone suggest how to effectively collect and format these validation errors from nested DTOs in Spring MVC? Any insights or examples would be appreciated! I recently upgraded to Java LTS. The project is a microservice built with Java. For reference, this is a production web app. Thanks in advance!