我是 CompletableFuture 世界的新手。我正在嘗試做一些負面測驗,以允許我故意拋出例外。此例外將決定通過/失敗。
這是代碼片段:
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);
}
});
}
這給了我一個錯誤,說在捕獲部分未處理的例外。我查閱了示例和檔案,但在 supplyAsync/whenCompleteAsync 中找不到有關例外處理的太多資訊。提前致謝。
uj5u.com熱心網友回復:
解決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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453898.html
