我有一个非常好奇的情况。
我正在尝试执行 EJB 的方法并使用 JAX-RS 返回结果
public Service readSingle(...) {
try {
service.query(...);
} catch (final NoResultException nre) {
throw new NotFoundException(...);
} catch (final NonUniqueResultException nure) {
throw new BadRequstException(...);
}
}
查询方法需要一些值以及一个 BiFuction
和一个 Function
。
实际的调用如下所示。
try {
return serviceService.<Service>query(
id,
ofNullable(matrixParameters.getFirst("onid"))
.map(Integer::parseInt).orElse(null),
ofNullable(matrixParameters.getFirst("tsid"))
.map(Integer::parseInt).orElse(null),
ofNullable(matrixParameters.getFirst("sid"))
.map(Integer::parseInt).orElse(null),
ofNullable(matrixParameters.getFirst("number"))
.map(Integer::parseInt).orElse(null),
ofNullable(matrixParameters.getFirst("programId"))
.orElse(null),
operatorId,
(builder, root) -> emptyList(),
TypedQuery::getSingleResult);
} catch (final NoResultException nre) {
throw new NotFoundException(
"no entity idnetified by " + serviceIdSegment.getPath()
+ " with " + matrixParameters.toString());
} catch (final NonUniqueResultException nure) {
throw new BadRequestException("multiple entities identified");
}
好的,我传递了 TypedQuery::getSingleResult
,并且我希望 NonUniqueResultException
在必须抛出时应该被捕获。
但是 Payara 一直响应 500,并且日志显示 NonUniqueResultException
从未被代码捕获。
我禁用了 ExceptionMappers,结果是相同的。
最佳答案
好的。我想到了。我必须这样做。
try {
// execute EJB
} catch (final EJBTransactionRolledbackException ejbtre) {
Exception leaf = ejbtre;
try {
for (Exception c;
(c = ((EJBException) leaf).getCausedByException()) != null;
leaf = c);
} catch (final ClassCastException cce) {
}
logger.severe("causedByException: " + leaf);
if (leaf instanceof NoResultException) {
throw new NotFoundException(
"no entity idnetified by " + serviceIdSegment.getPath()
+ " with " + matrixParameters.toString());
} else if (leaf instanceof NonUniqueResultException) {
throw new BadRequestException(
"multiple entities identified by "
+ serviceIdSegment.getPath()
+ " with " + matrixParameters.toString());
}
throw new InternalServerErrorException(ejbtre);
}
这远远超出了我的预期。 EJB的方法设计不好。
有什么方法可以更简单地做到这一点吗?
关于java - 如何从 EJB 捕获运行时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38453108/