gpt4 book ai didi

java - 让 CompletableFuture 异常()处理 supplyAsync() 异常

转载 作者:行者123 更新时间:2023-12-04 08:32:59 27 4
gpt4 key购买 nike

问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionallyCompletableFuture#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 ?

最佳答案

这可能不是一个 super 流行的库,但我们在内部使用它(有时我也在那里做一些工作;虽然次要):NoException .写得真好,符合我的口味。这不是它唯一的东西,但绝对涵盖了您的用例:
这是一个示例:

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

关于java - 让 CompletableFuture 异常()处理 supplyAsync() 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64937499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com