gpt4 book ai didi

java - CompletableFuture 异常处理程序链

转载 作者:行者123 更新时间:2023-11-29 09:31:39 25 4
gpt4 key购买 nike

是否可以使用 ComplatableFuture 在链中创建特殊处理程序?例如:我有这段代码,想法是如果位置服务方法抛出错误,则对 findClosest 方法进行通用调用(不带参数)。所以基本上,我想从这些方法中的任何一个返回 List 。这工作正常。但是在外部代码上,我需要触发一个事件以防方法调用是通用的(以防 locationService 失败)。

@Async
@Override
public CompletionStage<List<Closest>> getClosestByZip(final String zip) {

return locationService.getCoordinates(zip)
.handle((c, ex) -> ex == null ? closestService.findClosest(c) : closestService.findClosest())
.thenCompose(list -> list);
}

在测试中,异常部分从未执行,因为 future 似乎已成功完成。

CompletableFuture<List<Closest>> closest = distanceService.getClosestByZip("111111")
.exceptionally(ex -> {
System.out.println("From exceptionally");
return null;
})
.toCompletableFuture();


try {
List<Closest> list = closest.get();
Assert.assertEquals(2, list.size());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
Assert.fail("Exception was not caught");
}

如何处理这种情况?

最佳答案

请检查这是否有帮助。

public class CompleteableFutureEx {

public static void main(String[] args) throws Throwable {
try {
test(-1);
} catch (ArithmeticException e) {
System.out.println("Oops! We have an ArithmeticException");
}
catch (IllegalArgumentException e) {
System.out.println("Oops! We have an IllegalArgumentException");
}
catch (Exception e) {
System.out.println("Oops! We have an Exception ");

}
}

public static void test(int age) throws Throwable {

try {
CompletableFuture<String> maturityFuture = CompletableFuture.supplyAsync(() -> {
//ArithmeticException
//int age1 = age/0;
if (age < 0) {
throw new IllegalArgumentException("Age can not be negative");
}
if (age > 18) {
return "Adult";
} else {
return "Child";
}
});
maturityFuture.join();
}catch (CompletionException ce) {
throw ce.getCause();
}

}

}

关于java - CompletableFuture 异常处理程序链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49671358/

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