Uploaded image for project: 'Bean Validation'
  1. BVAL-198

Simplify creation of ConstraintViolationExceptions

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: 1.0 final
    • Fix Version/s: 1.1.0.Beta2
    • Component/s: spec-general
    • Labels:
      None
    • Last commented by a user?:
      true
    • Sprint:

      Description

      javax.validation.ConstraintViolationException wraps a set of constraint violations, currently in the following form:

      Set<ConstraintViolation<?>> constraintViolations
      

      As the exception's constructors have a parameter of the same type, instantiating it is not as easy as expected:

      Validator validator = ...;
      DomainObject domainObject = new DomainObject();
      Set<ConstraintViolation<DomainObject>> constraintViolations = validator.validate(domainObject);
      
      //compiler error: ("The constructor ConstraintViolationException(Set<ConstraintViolation<DomainObject>>) is undefined")
      throw new ConstraintViolationException(constraintViolations);
      
      //this works
      throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(constraintViolations));
      

      This problem can be solved by changing the collection type to

      Set<? extends ConstraintViolation<?>>
      

      The exception then would read as follows:

      public class ConstraintViolationException extends ValidationException {
      	private final Set<? extends ConstraintViolation<?>> constraintViolations;
      
      	public ConstraintViolationException(String message, Set<? extends ConstraintViolation<?>> constraintViolations) {
      		super( message );
      		this.constraintViolations = constraintViolations;
      	}
      
      	public ConstraintViolationException(Set<? extends ConstraintViolation<?>> constraintViolations) {
      		super();
      		this.constraintViolations = constraintViolations;
      	}
      
      	public Set<ConstraintViolation<?>> getConstraintViolations() {
      		return new HashSet<ConstraintViolation<?>>(constraintViolations);
      	}
      }
      

      This makes the exception easier to use for producers, while maintaining simplicity for clients (since getConstraintViolations() still returns a Set<ConstraintViolation<?>>, clients don't have to do deal with the bound wildcard expression).

        Attachments

          Issue links

            Activity

              People

              • Votes:
                6 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: