gpt4 book ai didi

java - 如何处理CompletableFuture中的异常并返回Integer值

转载 作者:行者123 更新时间:2023-11-30 05:28:49 25 4
gpt4 key购买 nike

我有一个方法,例如:

public Integer handleException(CompletableFuture<String> future)
throws ExecutionException, InterruptedException {

return future
.thenApply(Integer::parseInt)
.handle((result, ex) -> {
if (result != null) {
LOGGER.log(Level.INFO, ex.getMessage());
return null;
} else {
return 42;
}
});
}

我想处理我的 CompletableFuture<String> 中的异常。我想要做的就是在发生异常情况时记录异常错误并返回 -1,如果没有错误,我想返回 1。我的代码看似有效,但句柄方法中的整个表达式都带有错误下划线:

enter image description here

我有一个方法,例如:

return future
.thenApply(Integer::parseInt)
.exceptionally(
s -> {
LOGGER.log(Level.INFO, "ASD");
s.printStackTrace();
return -1;
})
.get();

它有效,但据说这不是异常处理的最佳解决方案,这就是我决定使用handle()方法的原因。对于我在handle()方法中做错了什么的建议,我将不胜感激。

最佳答案

函数handleException声明返回Integer ,当您尝试返回 CompletableFuture<Integer> 时。可能忘记了.get() ...

关于java - 如何处理CompletableFuture中的异常并返回Integer值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57998547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com