hibernate-validator throwing different exceptions in version 4 and 5

1.9k Views Asked by At

I am doing a spring boot rest application with a custom exception mapping. The exception mapping is irrelevant, but I wanted to use hibernate validator in version 4 ((because I have to use java validation api version 1.0).

Now I am initializing the validators in @configuration class:

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

@Bean
MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
    processor.setValidator(validator);
    return processor;
}

And I create a resource:

@Path("/validation")
@Produces("application/json")
@Validated
public interface ValidationTestResource {
    @POST
    @Path("/test")
    @Validated
    public void translatedAndMappedException(@RequestBody @Valid 
         ValidationTestDto testDto);
    }
}

The resource works. And the validation works. But whenever I violate the constraints on ValidationTestDto I get an exception. However this is org.hibernate.validator.method.MethodConstraintViolationException and it only specified which method and which parameter failed to validate (translatedAndMappedException, argument testDto). This makes it kind of useless to return the violated field list, as such list is not present.

But If I use hibernate-validator version 5+ I get a proper javax.validation.ConstraintViolationException and I can extract a full list of fields that were not validated.

The question is:

1.If I am simply doing something wrong, and Hibernate validator 4 is like that.

2.If I can use something from spring to validate and forget about hibernate-validator that would do it properly?

1

There are 1 best solutions below

0
On

Spring provides its own validation interfaces, so you can try using those directly. The documentation is here. You can use a BindingResult to see the details of the validation errors that are produced.