La pregunta es bastante simple: estoy buscando una forma elegante de usar CompletableFuture#exceptionally junto con CompletableFuture#supplyAsync . Esto es lo que no funciona:
private void doesNotCompile() { CompletableFuture<String> sad = CompletableFuture .supplyAsync(() -> throwSomething()) .exceptionally(Throwable::getMessage); } private String throwSomething() throws Exception { throw new Exception(); } Pensé que la idea detrás de exceptionally() era precisamente manejar los casos en los que se lanza una Exception . Sin embargo, si hago esto, funciona:
private void compiles() { CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> { try { throwSomething(); return ""; } catch (Exception e) { throw new RuntimeException(e); } }).exceptionally(Throwable::getMessage); } Podría trabajar con eso, pero se ve horrible y hace que las cosas sean más difíciles de mantener. ¿No hay una manera de mantener esto limpio que no requiera transformar todas las Exception en RuntimeException ?
Puede que esta no sea una biblioteca muy popular, pero la usamos (y de vez en cuando también hago algún trabajo allí; aunque menor) internamente: NoException . Está muy, muy bien escrito para mi gusto. Esto no es lo único que tiene, pero definitivamente cubre su caso de uso:
Aquí hay una muestra:
import com.machinezoo.noexception.Exceptions; import java.util.concurrent.CompletableFuture; public class SO64937499 { public static void main(String[] args) { CompletableFuture<String> sad = CompletableFuture .supplyAsync(Exceptions.sneak().supplier(SO64937499::throwSomething)) .exceptionally(Throwable::getMessage); } private static String throwSomething() throws Exception { throw new Exception(); } }O puede crear estos por su cuenta:
final class CheckedSupplier<T> implements Supplier<T> { private final SupplierThatThrows<T> supplier; CheckedSupplier(SupplierThatThrows<T> supplier) { this.supplier = supplier; } @Override public T get() { try { return supplier.get(); } catch (Throwable exception) { throw new RuntimeException(exception); } } } @FunctionalInterface interface SupplierThatThrows<T> { T get() throws Throwable; }Y uso:
CompletableFuture<String> sad = CompletableFuture .supplyAsync(new CheckedSupplier<>(SO64937499::throwSomething)) .exceptionally(Throwable::getMessage);