'Map exception in completable future to a different exception type?

I'm using java 8's completable futures and I'd like to be able take an exception that is throwing by the future and transform it to a different exception.

All the composite stuff I've tried seems to get short circuited once an exception occurs.

Using a scala future, for example, I can do something like this:

scala.concurrent.Future<Object> translatedException = ask.recover(new Recover<Object>() {
            @Override public Object recover(final Throwable failure) throws Throwable {
                if (failure instanceof AskTimeoutException) {
                    throw new ApiException(failure);
                }

                throw failure;
            }
        }, actorSystem.dispatcher());

and I'd like to be able to mimic that in a future composite block in java. Is this possible?



Solution 1:[1]

Please note that e will always be a java.util.concurrent.CompletionException.

CompletableFuture<String> ask = CompletableFuture.supplyAsync(() -> {
    throw new IndexOutOfBoundsException();
});
CompletableFuture<String> translatedException = ask.handle((r, e) -> {
    if (e != null) {
        if (e.getCause() instanceof IndexOutOfBoundsException) {
            throw new IllegalArgumentException();
        }
        throw (RuntimeException) e; // this is sketchy, handle it differently, maybe by wrapping it in a RuntimeException
    }
    return r;
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thomas