I read many tutorials about JSR 303 spec, but I don’t see any example ready for production. Everywhere described how to get Set<Constraintviolation<T>> object.
Example:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Car>> violations = validator.validate(car);
But what next? I want to inform method caller (client) that method parameter is in inconsistent state.
What I must do with Set<ConstraintViolation<Car>>? I need manually iterate over Set<ConstraintViolation>, collecting all error messages into one string, and then throw an exception with this messages?
Or exist some more convenient ways out of the box?
Or it’s better to provide validate method inside each bean?
I would go with your first suggestion – iterate over the constraint violations. You don’t necessarily create an error message that contains all that stuff. It is probably a good idea to just have an error message saying
bean <bean> is not validand set the constraint violations as a property on an exception.Maybe you need to convert the constraint violations to another object, because otherwise you would make much of your application dependent on the bean validation api. That might be a too strong coupling.
Your problem is that it is very use case specific what to do with the constraint violations. There are many cases where you don’t want to inform the caller about the constraint violations, but some other object. For example in a web form you want to inform your view model that it should also display these constraint violations. Throwing an exception is just another thing. Note that this won’t be a
ConstraintViolationExceptionin most cases, but a application specific exception.