ApiExceptions { public static <ResponseT> ResponseT callAndTranslateApiException(ApiFuture<ResponseT> future) { try { return Futures.getUnchecked(future); } catch (UncheckedExecutionException exception) { if (exception.getCause() instanceof RuntimeException) { RuntimeException cause = (RuntimeException) exception.getCause(); cause.addSuppressed(new AsyncTaskException()); throw cause; } throw exception; } } private  ApiExceptions(); static ResponseT callAndTranslateApiException(ApiFuture<ResponseT> future);  }
@Test public void noException() { Integer result = ApiExceptions.callAndTranslateApiException(ApiFutures.immediateFuture(2)); assertThat(result).isEqualTo(2); }
@Test public void throwsApiException() { Exception throwable = new UnavailableException(null, FakeStatusCode.of(StatusCode.Code.UNAVAILABLE), false); try { ApiExceptions.callAndTranslateApiException(ApiFutures.immediateFailedFuture(throwable)); Assert.fail("ApiExceptions should have thrown an exception"); } catch (ApiException expected) { assertThat(expected).isSameInstanceAs(throwable); } }
@Test public void throwsIOException() { try { ApiExceptions.callAndTranslateApiException( ApiFutures.immediateFailedFuture(new IOException())); Assert.fail("ApiExceptions should have thrown an exception"); } catch (UncheckedExecutionException expected) { assertThat(expected).hasCauseThat().isInstanceOf(IOException.class); } }
@Test public void throwsRuntimeException() { try { ApiExceptions.callAndTranslateApiException( ApiFutures.immediateFailedFuture(new IllegalArgumentException())); Assert.fail("ApiExceptions should have thrown an exception"); } catch (IllegalArgumentException expected) { assertThat(expected).isInstanceOf(IllegalArgumentException.class); } }
@Test public void containsCurrentStacktrace() { final String currentMethod = "containsCurrentStacktrace"; ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); ListenableFuture<?> futureError = executor.submit( new Runnable() { @Override public void run() { throw new IllegalArgumentException(); } }); ListenableFutureToApiFuture<?> futureErrorWrapper = new ListenableFutureToApiFuture<>(futureError); executor.shutdown(); Exception actualError = null; try { ApiExceptions.callAndTranslateApiException(futureErrorWrapper); } catch (Exception e) { actualError = e; } assertThat(actualError).isNotNull(); assertThat(isMethodInStacktrace(currentMethod, actualError)).isFalse(); assertThat(actualError.getSuppressed()[0]).isInstanceOf(AsyncTaskException.class); assertThat(isMethodInStacktrace(currentMethod, actualError.getSuppressed()[0])).isTrue(); }