diff --git a/src/main/java/com/google/api/core/ApiFutures.java b/src/main/java/com/google/api/core/ApiFutures.java index d0638f1f6..d02892619 100644 --- a/src/main/java/com/google/api/core/ApiFutures.java +++ b/src/main/java/com/google/api/core/ApiFutures.java @@ -104,6 +104,27 @@ public static ApiFuture catching( return new ListenableFutureToApiFuture(catchingFuture); } + @BetaApi + public static ApiFuture catchingAsync( + ApiFuture input, + Class exceptionType, + final ApiAsyncFunction callback, + Executor executor) { + ListenableFuture catchingFuture = + Futures.catchingAsync( + listenableFutureForApiFuture(input), + exceptionType, + new AsyncFunction() { + @Override + public ListenableFuture apply(X exception) throws Exception { + ApiFuture result = callback.apply(exception); + return listenableFutureForApiFuture(result); + } + }, + executor); + return new ListenableFutureToApiFuture<>(catchingFuture); + } + public static ApiFuture immediateFuture(V value) { return new ListenableFutureToApiFuture<>(Futures.immediateFuture(value)); } diff --git a/src/test/java/com/google/api/core/ApiFuturesTest.java b/src/test/java/com/google/api/core/ApiFuturesTest.java index eec0fd8f3..de10b7ee8 100644 --- a/src/test/java/com/google/api/core/ApiFuturesTest.java +++ b/src/test/java/com/google/api/core/ApiFuturesTest.java @@ -83,6 +83,24 @@ public Integer apply(Exception ex) { assertThat(fallback.get()).isEqualTo(42); } + @Test + public void testCatchAsync() throws Exception { + SettableApiFuture future = SettableApiFuture.create(); + ApiFuture fallback = + ApiFutures.catchingAsync( + future, + Exception.class, + new ApiAsyncFunction() { + @Override + public ApiFuture apply(Exception ex) { + return ApiFutures.immediateFuture(42); + } + }, + directExecutor()); + future.setException(new Exception()); + assertThat(fallback.get()).isEqualTo(42); + } + @Test public void testTransform() throws Exception { SettableApiFuture inputFuture = SettableApiFuture.create();