我想使用 jooby 验证我查看了https://jooby.org/doc/hbv/但我不能使用它
1 回答
0
- 您需要在 App 类中 初始化Hibernate Validator 。
use(new Hbv(ClassUtils.getClasses("com.package.of.classes.validate")));
- 使用验证器注释您的类。请注意,这些类必须在上述包中。例子:
public class SampleRequest {
@NotNull
private Long id;
@NotBlank
String name;
private @NotBlank
String description;
private @Min(1)
double amount;
}
- 然后,您可以在 App 类中使用通用错误处理程序。
err((req, rsp, err) -> {
Throwable cause = err.getCause();
if (cause instanceof ConstraintViolationException) {
Set<ConstraintViolation<?>> constraints = ((ConstraintViolationException) cause)
.getConstraintViolations();
// handle errors, return error response
} else {
// ......
}
});
- 或者您可以在您的服务中手动验证:
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());
}
}
于 2019-05-04T21:52:57.707 回答