我没有找到问题的答案"如何处理方法验证异常?&#34 ;,这是由Bean Validation 1.1自动抛出的。
我有以下环境:
Glassfish 4
hibernate-validator-5.0.1.Final.jar (in ear)
现在我尝试实现方法参数的自动验证:
@Local
@ValidateOnExecution(type = ExecutableType.ALL)
public interface SomeServiceLocal {
String someMethod(@Size(max = 1) String value);
}
执行:
@Stateless
public class OtherBean implements OtherBeanLocal {
@EJB
private SomeServiceLocal someService;
@Override
public String otherMethod() {
return someService.someMethod("abc");
}
}
}
现在,当我将otherMethod称为receive:
javax.ejb.EJBTransactionRolledbackException
at com.sun.ejb.containers.BaseContainer.mapLocal3xException(BaseContainer.java:2279)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2060)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
接着是
Caused by: javax.validation.ConstraintViolationException: 1 constraint violation(s) occurred during method validation
...
Constraint violations:
(1) Kind: PARAMETER
parameter index: 3
message: size must be between 0 and 1
处理违规例外的最佳做法是什么?
答案 0 :(得分:0)
我创建了cdi拦截器,它处理EJBException并提取约束违规。它完美无缺:
@MyValidation
@Interceptor
public class MyValidationExceptionInterceptor implements Serializable {
private static final long serialVersionUID = -5280505156146359055L;
@AroundInvoke
public Object processViolationException(InvocationContext ctx) throws Exception {
try {
return ctx.proceed();
} catch (EJBTransactionRolledbackException e) {
Throwable throwable = e.getCause();
if (throwable != null && throwable.getCause() != null && throwable.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException) throwable.getCause();
throw new MyException(getMessage(cve));
}
throw e;
} catch (Exception e) {
throw e;
}
}
private String getMessage(ConstraintViolationException cve) {
StringBuilder builder = new StringBuilder();
for(ConstraintViolation<?> violation : cve.getConstraintViolations()) {
builder.append(violation.getMessage()).append(';');
}
return builder.toString();
}
}