英文:
Java: How to tell if API Completable Future errored out
问题
如何判断一个Completeable Future是否失败并带有错误?我正试图查看下面的Java Future库以找出答案。不确定应该选择哪个。
目前,当一个成功,一个失败时,我试图找出哪个API出现了错误。
CompletableFuture<ProductResponse> productFuture = CompletableFuture.supplyAsync(() ->
productAPI(productRequest)
);
CompletableFuture<VendorResponse> vendorFuture= CompletableFuture.supplyAsync(() ->
vendorAPI.postLogin(vendorRequest)
);
try {
CompletableFuture.allOf(productFuture, vendorFuture).join();
} catch (Exception e) {
}
英文:
How do I tell if a Completeable Future failed with an error? I am trying to look through Java Future Library below and find out? Not sure which one to pick.
Right now, when one succeeds, and one fails, trying to find which API had the error.
CompletableFuture<ProductResponse> productFuture = CompletableFuture.supplyAsync(() ->
productAPI(productRequest)
);
CompletableFuture<VendorResponse> vendorFuture= CompletableFuture.supplyAsync(() ->
vendorAPI.postLogin(vendorRequest)
);
try {
CompletableFuture.allOf(productFuture , vendorFuture).join();
} catch (Exception e) {
}
答案1
得分: 2
你可以通过在完成后检查 isCompletedExceptionally()
来检查特定的未来是否失败:
if (productFuture.isCompletedExceptionally()) {
System.out.println("product request failed!");
}
或者通过使用 get()
捕获 ExecutionException
:
try {
productFuture.get();
} catch (ExecutionException e) {
System.out.println("product request failed!");
}
或者你可以通过 exceptionally()
或 whenComplete()
来设置一个失败回调:
productFuture = productFuture.whenComplete(
(res, exc) -> System.out.println("product request failed!"));
英文:
You can check if a specific future failed by checking isCompletedExceptionally()
after it's done:
if (productFuture.isCompletedExceptionally()) {
System.out.println("product request failed!");
}
Or by catching the ExecutionException
via get()
:
try {
productFuture.get();
} catch (ExecutionException e) {
System.out.println("product request failed!");
}
Or you can set a failure callback via exceptionally()
or whenComplete()
:
productFuture = productFuture.whenComplete(
(res, exc) -> System.out.println("product request failed!"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论