java - 未处理的异常在两种不同的方法上的工作方式不同
问题描述
我Unhandled exception works differently on two different methods
采用了第二种方法,getByIds
这是没有意义的。我在第二种方法中调用第一种方法并已经把try catch。
这个例外有什么想法吗?谢谢
@Override
public PostPayload getById(@NotNull UUID issueId) throws APIException {
try (...) {
return test.apply(responseIssue, issueAuxiliaryData);
} catch (IOException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);
}
}
@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
解决方案
除了例外,您可以做两件事:
- 以某种方式处理它
- 重新
throw
_
你的第一个方法throws APIException
在它的签名中有一个,所以抛出APIException
是一个有效的事情。
但这与您的其他方法有何不同?在那里,您试图从传递给stream().map()
方法的 lambda 中抛出异常。从文档中我们可以找到这个 lambda 对应的功能接口:
public interface Function<T, R> {
R apply(T t);
}
从签名中我们可以看到它没有抛出任何已检查的异常,因此APIException
从 lambda 中抛出是编译错误(假设APIException
是已检查的异常)
一种可能的解决方法是定义另一个版本的异常,RuntimeException
例如从UncheckedApiException
. 然后你可以将整个流操作包装在一个大的 try-catch 块中,然后在 catch 块中你可以抛出检查的版本:
@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
try {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new UncheckedApiException("Unable to retrieve XXX for issueId=" + issueId, e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} catch (UncheckedApiException e) {
throw new APIException(e);
}
}
推荐阅读
- html - XSL - HTML 表格页脚在位置动态显示(根据表格中的行数更改)
- python - Mac OS High Sierra 上 Miniconda 的 CERN ROOT:libpng 冲突
- mysql - 对现有架构执行迁移时出现 Django 迁移错误
- java - 恢复活动
- spring - Spring 5+ Hibernate 5 + Atomikos 4 + Tomcat 的集成 无法定位当前 JTA 事务
- html - CSS响应式定位内联元素的方式
- node.js - 在 mongoDB 中更新数据库后查询不给出更新的结果
- sonarqube - 如何在 AWS elasticbeanstalk 中配置 sonarqube 7.1
- python - Python - 多处理最大进程数
- android - 使用 Android Jetpack 从导航抽屉导航