The question is rather simple: I'm looking for an elegant way of using CompletableFuture#exceptionally
alongside with CompletableFuture#supplyAsync
. This is what does not work:
private void doesNotCompile() {
CompletableFuture<String> sad = CompletableFuture
.supplyAsync(() -> throwSomething())
.exceptionally(Throwable::getMessage);
}
private String throwSomething() throws Exception {
throw new Exception();
}
I thought the idea behind exceptionally()
was precisely to handle cases where an Exception
is thrown. Yet if I do this it works:
private void compiles() {
CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> {
try {
throwSomething();
return "";
} catch (Exception e) {
throw new RuntimeException(e);
}
}).exceptionally(Throwable::getMessage);
}
I could work with that, but it looks horrible and makes things harder to maintain. Is there not a way to keep this clean which doesn't require transforming all the Exception
into RuntimeException
?