如何找到异常完成的 CompletableFuture
How to find CompletableFuture completed execeptionally
我正在使用 CompletableFuture,对异常处理有疑问。
我有一个这样的代码,如果任何 validate() 或 process() 方法抛出异常,那么它由 ExceptionHandler 处理。但是,当我像这样使用 CompletableFuture 时,抛出的异常被包装在 CompletionException 中。我可以知道如何确保在那里调用我的 ExceptionHandler 而不是获取 CompletionException 吗?
CompletableFuture<Response> response = CompletableFuture
.supplyAsync(() -> {
validationService.validate(request);
return myService.process(request, headers);
});
知道了,调用下面的代码就可以解决我的问题
try {
response.join();
}
catch(CompletionException ex) {
try {
throw ex.getCause();
}
catch(Throwable impossible) {
throw impossible;
}
}
在 CompletableFuture
上调用 get()
之前调用此方法 isCompletedExceptionally
,如果它完成并出现异常 return 将 return 为真
public boolean isCompletedExceptionally()
Returns true if this CompletableFuture completed exceptionally, in any way. Possible causes include cancellation, explicit invocation of completeExceptionally, and abrupt termination of a CompletionStage action.
您还可以为 completableFuture 添加异常块,因此在执行任务时,如果发生任何异常,它将异常执行异常输入参数
CompletableFuture<String> future = CompletableFuture.supplyAsync(()-> "Success")
.exceptionally(ex->"failed");
在上面的示例中,如果执行 supplyAsync
failed 发生任何异常,将 return 否则 Success 是returned
我正在使用 CompletableFuture,对异常处理有疑问。
我有一个这样的代码,如果任何 validate() 或 process() 方法抛出异常,那么它由 ExceptionHandler 处理。但是,当我像这样使用 CompletableFuture 时,抛出的异常被包装在 CompletionException 中。我可以知道如何确保在那里调用我的 ExceptionHandler 而不是获取 CompletionException 吗?
CompletableFuture<Response> response = CompletableFuture
.supplyAsync(() -> {
validationService.validate(request);
return myService.process(request, headers);
});
知道了,调用下面的代码就可以解决我的问题
try {
response.join();
}
catch(CompletionException ex) {
try {
throw ex.getCause();
}
catch(Throwable impossible) {
throw impossible;
}
}
在 CompletableFuture
上调用 get()
之前调用此方法 isCompletedExceptionally
,如果它完成并出现异常 return 将 return 为真
public boolean isCompletedExceptionally()
Returns true if this CompletableFuture completed exceptionally, in any way. Possible causes include cancellation, explicit invocation of completeExceptionally, and abrupt termination of a CompletionStage action.
您还可以为 completableFuture 添加异常块,因此在执行任务时,如果发生任何异常,它将异常执行异常输入参数
CompletableFuture<String> future = CompletableFuture.supplyAsync(()-> "Success")
.exceptionally(ex->"failed");
在上面的示例中,如果执行 supplyAsync
failed 发生任何异常,将 return 否则 Success 是returned