簡體   English   中英

如何抽象捕獲的異常CompletableFutures以調用方法

[英]How to abstract catching exceptions CompletableFutures for invoking a method

好的,我有類似的方法

  1. CompletableFuture fetchCar(int id);
  2. CompletableFuture runSomething(t的東西,Extra d);
  3. CompletableFuture invoke();

我想使用一種可以執行以下操作的方法,以便它將將來轉換的所有同步異常都轉換為

private CompletableFuture<Void> invokeSomething(Something something) {
    CompletableFuture<Void> future;
    try {
        future = something.runSomething(t, d);
    } catch(Throwable e) {
        future = new CompletableFuture<Void>();
        future.completeExceptionally(e);
    }

    return future;
}

請注意,我只是碰巧選擇了#2作為示例,但我想使用通用名稱,因此我可以停止鍵入,因為一般來說,它需要偶爾執行一次,以確保您以相同的方式處理同步和異步異常。

我不確定這是您要找的東西,但是您可以創建一個實用程序函數:

public static <T> CompletableFuture<T> foo(Callable<CompletableFuture<T>> callable) {
    try {
        return callable.call();
    } catch (Exception ex) {
        return CompletableFuture.failedFuture(ex);
    }
}

然后,您可以像這樣使用它:

Something something = ...;
CompletableFuture<Void> future = foo(() -> invokeSomthing(something));

一些注意事項:

  1. 之所以使用Callable是因為其功能方法call可以拋出Exception 如果使用諸如Supplier東西,那么將其與可能引發檢查異常的方法一起使用將是混亂的。
  2. 使用catch (Exception ex)而不是catch (Throwable ex)因為Callable#call不會拋出Throwable ,並且通常認為捕獲ErrorError的做法。 如果需要,您始終可以將其更改為Throwable
  3. 如果callablenull ,則此實用程序方法將返回由NPE導致的失敗的將來; 不知道這是否是理想的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM