让completablefuture()处理supplySync()异常

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

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

private void doesNotCompile() {
    CompletableFuture<String> sad = CompletableFuture
            .supplyAsync(() -> throwSomething())
            .exceptionally(Throwable::getMessage);
}

private String throwSomething() throws Exception {
    throw new Exception();
}

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

private void compiles() {
    CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> {
        try {
            throwSomething();
            return "";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }).exceptionally(Throwable::getMessage);
}

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

uubf1zoe

uubf1zoe1#

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

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();
    }
}

或者您可以自己创建:

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;
}

使用方法:

CompletableFuture<String> sad = CompletableFuture
        .supplyAsync(new CheckedSupplier<>(SO64937499::throwSomething))
        .exceptionally(Throwable::getMessage);

相关问题