Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
Permitir que CompletableFuture excepcionalmente() maneje una excepción supplyAsync()

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 ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda