I want to use jooby validation I looked through https://jooby.org/doc/hbv/ but I can't use it
Asked
Active
Viewed 138 times
1 Answers
0
- You need to initialise Hibernate Validator in the App class.
use(new Hbv(ClassUtils.getClasses("com.package.of.classes.validate")));
- Annotate your classes with the validators. Note these classes have to be in the above package. Example:
public class SampleRequest {
@NotNull
private Long id;
@NotBlank
String name;
private @NotBlank
String description;
private @Min(1)
double amount;
}
- You can then use a general error handler in the App class.
err((req, rsp, err) -> {
Throwable cause = err.getCause();
if (cause instanceof ConstraintViolationException) {
Set<ConstraintViolation<?>> constraints = ((ConstraintViolationException) cause)
.getConstraintViolations();
// handle errors, return error response
} else {
// ......
}
});
- Or you can manually validate in your service:
private void validateRequest(SampleRequest sampleRequest) {
Validator validator = factory.getValidator();
Set<ConstraintViolation<SampleRequest>> constraintViolations =
validator.validate(sampleRequest);
if (!constraintViolations.isEmpty()) {
StringBuilder builder = new StringBuilder();
for (ConstraintViolation<SampleRequest> error : constraintViolations) {
logger.error(error.getPropertyPath() + "::" + error.getMessage());
builder.append(error.getPropertyPath() + "::" + error.getMessage());
}
throw new IllegalArgumentException(builder.toString());
}
}

rogaroga
- 11
- 2