让completablefuture()处理supplySync()异常

watbbzwu  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(522)

问题很简单:我在寻找一种优雅的使用方法 CompletableFuture#exceptionally 与…并排 CompletableFuture#supplyAsync . 这是行不通的:

  1. private void doesNotCompile() {
  2. CompletableFuture<String> sad = CompletableFuture
  3. .supplyAsync(() -> throwSomething())
  4. .exceptionally(Throwable::getMessage);
  5. }
  6. private String throwSomething() throws Exception {
  7. throw new Exception();
  8. }

我想这背后的想法 exceptionally() 正是为了处理 Exception 被抛出。但如果我这么做的话:

  1. private void compiles() {
  2. CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> {
  3. try {
  4. throwSomething();
  5. return "";
  6. } catch (Exception e) {
  7. throw new RuntimeException(e);
  8. }
  9. }).exceptionally(Throwable::getMessage);
  10. }

我可以用它,但它看起来很可怕,使事情更难维持。有没有一种方法可以保持这种清洁,而不需要改变所有的 Exception 进入 RuntimeException ?

uubf1zoe

uubf1zoe1#

这可能不是一个超级流行的图书馆,但我们使用它(有时我也在那里做一些工作;轻微的)内部:无例外。它真的,真的很适合我的口味。这不是它所拥有的唯一东西,但肯定涵盖了您的用例:
以下是一个示例:

  1. import com.machinezoo.noexception.Exceptions;
  2. import java.util.concurrent.CompletableFuture;
  3. public class SO64937499 {
  4. public static void main(String[] args) {
  5. CompletableFuture<String> sad = CompletableFuture
  6. .supplyAsync(Exceptions.sneak().supplier(SO64937499::throwSomething))
  7. .exceptionally(Throwable::getMessage);
  8. }
  9. private static String throwSomething() throws Exception {
  10. throw new Exception();
  11. }
  12. }

或者您可以自己创建:

  1. final class CheckedSupplier<T> implements Supplier<T> {
  2. private final SupplierThatThrows<T> supplier;
  3. CheckedSupplier(SupplierThatThrows<T> supplier) {
  4. this.supplier = supplier;
  5. }
  6. @Override
  7. public T get() {
  8. try {
  9. return supplier.get();
  10. } catch (Throwable exception) {
  11. throw new RuntimeException(exception);
  12. }
  13. }
  14. }
  15. @FunctionalInterface
  16. interface SupplierThatThrows<T> {
  17. T get() throws Throwable;
  18. }

使用方法:

  1. CompletableFuture<String> sad = CompletableFuture
  2. .supplyAsync(new CheckedSupplier<>(SO64937499::throwSomething))
  3. .exceptionally(Throwable::getMessage);
展开查看全部

相关问题