0

I am developing a REST API and want to validate some @RequestParam using @Validated annotation of Spring.

But the problem is that @Validated results in ConstraintViolationException due to which I cannot get details of FieldError so that I can check which Field has error and give proper error object as per requested parameters.

Here is the sample code I am using for handling this validations:

Controller Class

@RestController
@Validated
public class Controller{

   @GetMapping("/getValue")
   public Response controller(@RequestParam @NotNull String username,
     @RequestParam String value, @RequestParam @NotNull @Size(max=21) String id, @RequestParam @Pattern(regexp="")String value){

   return responseObject;
}

ValidationHandlerClass

@ControllerAdvice
public class ControllerValidation{


@ExpectionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Set<ConstraintViolation> validateRequest(ConstraintViolationException e){

  return e.getConstraintViolations();
}

Can anyone help me how get FieldErrors in such Validation scenario.

Thanks in Advance.

Shashank_Itmaster
  • 2,465
  • 5
  • 30
  • 56
  • Possible duplicate of [Get field name when javax.validation.ConstraintViolationException is thrown](http://stackoverflow.com/questions/36555057/get-field-name-when-javax-validation-constraintviolationexception-is-thrown) – Vasu Nov 16 '16 at 06:21
  • @javaguy : If you follow the answers of the question, then it is solving the problem of what I am looking for. Thanks for help. – Shashank_Itmaster Nov 16 '16 at 07:31

1 Answers1

0

Thanks for the help. I got my answer my adding following as Configuration:

@Configuration
public class ConfigProps{

@Bean
public Validator validator(){
 return new LocalValidatorFactoryBean();
}

@Bean 
public MethodValidationPostProcesssor methodValidationPostProcessor(){
  MethodVaidationPostProccessor methodPostProcessor = new MethodValidationProcessor();
  methodPostProcessor.setValidator(validator());
  return methodPostProcessor;
}
Shashank_Itmaster
  • 2,465
  • 5
  • 30
  • 56
  • How does it actually solve it? Does `ConstraintViolationException` is being constructed differently? Please elaborate. – Ihor M. Jun 05 '19 at 20:09