@Async CompletableFuture#get 不抛出自定义运行时异常



我有这个方法:

@Async
@Override
public CompletableFuture<List<ProductDTO>> dashboard( ) throws GeneralException {
List<Product> products = newArrayList();
/*....
....*/
//I want this exception when calling CompletableFuture#get()
if ( products.isEmpty() ) {
throw new GeneralException( "user.not-has.product-message",
"user.not-has.product-title" );
}
return CompletableFuture
.completedFuture( ...) );
}

GeneralException是这样定义的:

public class GeneralException extends RuntimeException {...}

问题是,当抛出GeneralException时,当我调用CompletableFuture#get()以获取数据或异常时,我有一个java.util.concurrent.ExecutionException而不是我的自定义GeneralException。Spring doc 声称:

@Async方法具有Future类型返回值时,很容易 管理在方法执行期间引发的异常,如 对Future结果调用get时会引发此异常。

我做错了什么? 多谢

编辑:这是客户端代码:

public static <T> T retrieveDataFromCompletableFuture( @NotNull CompletableFuture<T> futureData ) {
T data = null;
try {
data = futureData.get();
} catch ( Exception e ) {
log.error( "Can't get data ", e );
}
return data;
}

例外情况:

java.util.concurrent.ExecutionException: org.app.exceptions.GeneralException: user.not-has.product-message
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
.....
Caused by: org.app.exceptions.GeneralException: user.not-has.product-message

为什么我还有java.util.concurrent.ExecutionException

尽量不要抛出异常,而是完成有异常的功能

@Async
@Override
public CompletableFuture<List<ProductDTO>> dashboard( ) throws GeneralException {
List<Product> products = newArrayList();
/*....
....*/
//I want this exception when calling CompletableFuture#get()
if ( products.isEmpty() ) {
CompletableFuture<List<ProductDTO>> result = new CompletableFeature<>();
result.completeExceptionally(new GeneralException("user.not-has.product-message", 
"user.not-has.product-title"
);
return result;
}
return CompletableFuture
.completedFuture( ...) );
}

最新更新