CompletableFuture:whenCompleteAsync() 不允许我重新抛出异常
CompletableFuture: whenCompleteAsync() does not let me re-throw an Exception
我是 CompletableFuture 的新手。我正在尝试进行一些负面测试,以允许我故意抛出异常的方式。此异常将决定 PASS/FAIL.
这是代码片段:
protected CompletableFuture<Response> executeAsync(@NonNull Supplier<Response> call) {
return CompletableFuture
.supplyAsync(call::get)
.whenCompleteAsync((response, exception) -> {
if (exception == null) {
try {
Helper.throwIfNotExpected(clientProperties.getName(), response, null);
} catch (ServiceException e) {
throw new ServiceException(null,e.getMessage(),null);
}
} else {
log.error("Async API call failed.", exception);
}
});
}
这给我一个错误,在 catch 部分显示 未处理的异常。我查阅了示例和文档,但在 supplyAsync/whenCompleteAsync 中找不到有关异常处理的太多信息。提前致谢。
解决 CompletableFuture
关于检查异常的缺点的一个好方法是委托给另一个 CompletableFuture
实例。对于您的示例,它看起来像
protected CompletableFuture<Response> executeAsync(Supplier<Response> call) {
CompletableFuture<Response> delegate = new CompletableFuture<>();
CompletableFuture
.supplyAsync(call)
.whenCompleteAsync((response, exception) -> {
if (exception == null) {
try {
Helper.throwIfNotExpected(clientProperties.getName(), response, null);
delegate.complete(response);
} catch (ServiceException e) {
delegate.completeExceptionally(new ServiceException(null,e.getMessage(),null));
}
} else {
log.error("Async API call failed.", exception);
delegate.completeExceptionally(exception);
}
});
return delegate;
}
我是 CompletableFuture 的新手。我正在尝试进行一些负面测试,以允许我故意抛出异常的方式。此异常将决定 PASS/FAIL.
这是代码片段:
protected CompletableFuture<Response> executeAsync(@NonNull Supplier<Response> call) {
return CompletableFuture
.supplyAsync(call::get)
.whenCompleteAsync((response, exception) -> {
if (exception == null) {
try {
Helper.throwIfNotExpected(clientProperties.getName(), response, null);
} catch (ServiceException e) {
throw new ServiceException(null,e.getMessage(),null);
}
} else {
log.error("Async API call failed.", exception);
}
});
}
这给我一个错误,在 catch 部分显示 未处理的异常。我查阅了示例和文档,但在 supplyAsync/whenCompleteAsync 中找不到有关异常处理的太多信息。提前致谢。
解决 CompletableFuture
关于检查异常的缺点的一个好方法是委托给另一个 CompletableFuture
实例。对于您的示例,它看起来像
protected CompletableFuture<Response> executeAsync(Supplier<Response> call) {
CompletableFuture<Response> delegate = new CompletableFuture<>();
CompletableFuture
.supplyAsync(call)
.whenCompleteAsync((response, exception) -> {
if (exception == null) {
try {
Helper.throwIfNotExpected(clientProperties.getName(), response, null);
delegate.complete(response);
} catch (ServiceException e) {
delegate.completeExceptionally(new ServiceException(null,e.getMessage(),null));
}
} else {
log.error("Async API call failed.", exception);
delegate.completeExceptionally(exception);
}
});
return delegate;
}