CompletableFuture: get object before exception was thrown

Viewed 66

I wonder whether it is possible to get the object that before exception was thrown. Consider the following code:

  Stream.of("String", null, "String2").forEach(
            str -> CompletableFuture.supplyAsync(str::length)
                .thenCompose(integer -> CompletableFuture
                    .supplyAsync(() -> integer * 2))
                .handle((result, thr) -> {
                    if (thr != null) {
                       // how to get access to str?
                    }
                }));

Note that this code is merely an example. Actual code is different. handle will give two arguments: exception (if it was thrown, and actual result of previous computation).

I wonder if an exception if thrown, I can get access to the result of first computation that finished without exception. In this case it would be "String" (for first iteration), null (for second iteration), "String2" (for third iteration).

I have gone through Java documentation and haven't found a way. If there is no way indeed, how would you rewrite the code to have access to the previous object?

0 Answers
Related