Skip to content

Commit

Permalink
Added new exception for constraint violations
Browse files Browse the repository at this point in the history
  • Loading branch information
michael-schnell committed Mar 2, 2024
1 parent 8f0c540 commit 18a7887
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.fuin.objects4j.core;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.constraints.NotEmpty;
import org.fuin.objects4j.common.Contract;

import java.util.Collections;
import java.util.Objects;
import java.util.Set;

/**
* On or more constraint violations are considered an error.
*/
public final class ConstraintViolationException extends Exception {

private final Set<ConstraintViolation<Object>> violations;

/**
* Constructor with mandatory data.
*
* @param violations Violations that caused the error.
*/
public ConstraintViolationException(@NotEmpty final Set<ConstraintViolation<Object>> violations) {
super(Contract.asString(violations, ", "));
this.violations = Objects.requireNonNull(violations, "violations==null)");
if (violations.isEmpty()) {
throw new IllegalArgumentException("List of violations is empty");
}
}

/**
* Returns the violations that caused the error.
*
* @return Immutable set of violations.
*/
@NotEmpty
public Set<ConstraintViolation<Object>> getViolations() {
return Collections.unmodifiableSet(violations);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.fuin.objects4j.core;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.junit.jupiter.api.Test;

import java.util.Set;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;

/**
* Test for the {@link ConstraintViolationException} class.
*/
class ConstraintViolationExceptionTest {

@Test
void testCreate() {

// GIVEN
try (final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory()) {
final Validator validator = validatorFactory.getValidator();
final Set<ConstraintViolation<Object>> violations = validator.validate(new Example());

// WHEN
final ConstraintViolationException testee = new ConstraintViolationException(violations);

// THEN
assertThat(testee.getViolations()).containsOnly(violations.toArray(new ConstraintViolation[0]));
assertThat(testee.getMessage()).contains("Example.name");
assertThat(testee.getMessage()).contains("Example.id");

}

}

private static final class Example {

@NotNull
private Integer id;

@NotEmpty
private String name;

}


}

0 comments on commit 18a7887

Please sign in to comment.