如何判断 Java API Completable Future 是否出错。

huangapple go评论65阅读模式
英文:

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) {
    
}

如何判断 Java API Completable Future 是否出错。

英文:

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&lt;ProductResponse&gt; productFuture = CompletableFuture.supplyAsync(() -&gt;
		productAPI(productRequest)
);
CompletableFuture&lt;VendorResponse&gt; vendorFuture= CompletableFuture.supplyAsync(() -&gt;
		vendorAPI.postLogin(vendorRequest)
);

try {
	CompletableFuture.allOf(productFuture , vendorFuture).join();
} catch (Exception e) {
	
}

如何判断 Java API Completable Future 是否出错。

答案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(&quot;product request failed!&quot;);
}

Or by catching the ExecutionException via get():

try {
    productFuture.get();
} catch (ExecutionException e) {
    System.out.println(&quot;product request failed!&quot;);
}

Or you can set a failure callback via exceptionally() or whenComplete():

productFuture = productFuture.whenComplete(
        (res, exc) -&gt; System.out.println(&quot;product request failed!&quot;));

huangapple
  • 本文由 发表于 2023年6月12日 12:26:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定