0

I have a Spring controller method that I wanna validate using @Valid and get the BindingResult errorlist. But In my @RequestBody have List list.

@PostMapping(path="/save/inouts")
public ResponseEntity<List<InoutResponse>> saveInouts(@Valid InoutWrapper inouts, BindingResults res){
.....
}

class InoutWrapper {
   private List<Inouts> inoutList;
//getters and //setters

}

So I need to get error list as well as each error has the reference to Inout object to make InoutResponse.

IsuruK
  • 55
  • 6

1 Answers1

1

You have 2 options, either remove the @valid annotation from the controller parameter and call the validation explicitly. Like below:

javax.validation.Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
final Set<ConstraintViolation<InoutWrapper>> constraints = validator.validate(inouts);

Or write an exception handler for your controller. I would prefer this one. Something like below:

@ControllerAdvice
class MyExceptionHandler extends ResponseEntityExceptionHandler {
  @Override
  protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
   HttpHeaders headers, HttpStatus status, WebRequest request) {
     // read ex.getBindingResult().
     return super.handleMethodArgumentNotValid(ex, headers, status, request);
    }
  }
Aditya Narayan Dixit
  • 2,105
  • 11
  • 23