> And R" /> > And R" /> > And R"/>

How split collection of validated objects in Spring and bean validation?

50 Views Asked by At

Consider:

@PostMapping("/track")
public void sendTopicCallback(@RequestBody @Validated Request request): CompletableFuture<ResponseEntity<Void>>

And Request is:

public class Request {
    @Valid
    private List<MyObjects> objects;
}

How to validate request but instead of returning 400 error code get valid object List and List of errors mapped with raw data?

1

There are 1 best solutions below

0
Johannes Becker On

I am sitting in the train and have no PC with me, so I can just point you in a direction.

What happens in Spring internally, is that a ConstraintViolationException is thrown. This exception contains all violations found by the validator. This information can be used to calculate the information you need.

Second thing that happens when an exception is thrown by a RestController it is handled by an exception handler which maps it to an appropiate http response. If no handler is defined a default handler is used.

There are multiple ways to define such a handler, this is best explained in the official documentation.

There you can define a handler for the ConstraintViolationException where you create your desired response.