sách gpt4 ai đã đi

Để CompletableFuture exception() xử lý ngoại lệ supplyAsync()

In lại 作者:行者123 更新时间:2023-12-04 08:32:59 27 4
mua khóa gpt4 Nike

问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionallyCompletableFuture#supplyAsync 一起.这是行不通的:

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

private String throwSomething() throws Exception {
throw new Exception();
}
我想到了背后的想法 exceptionally()正是为了处理 Ngoại lệ 的情况被抛出。但是,如果我这样做,它会起作用:
private void compiles() {
CompletableFuture thisIsFine = CompletableFuture.supplyAsync(() -> {
thử {
throwSomething();
return "";
} catch (Exception e) {
throw new RuntimeException(e);
}
}).exceptionally(Throwable::getMessage);
}
我可以使用它,但它看起来很糟糕并且使事情更难维护。有没有办法保持这种清洁而不需要转换所有 Ngoại lệĐi vào RuntimeException ?

1 Câu trả lời

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

import com.machinezoo.noexception.Exceptions;
import java.util.concurrent.CompletableFuture;

public class SO64937499 {

public static void main(String[] args) {
CompletableFuture sad = CompletableFuture
.supplyAsync(Exceptions.sneak().supplier(SO64937499::throwSomething))
.exceptionally(Throwable::getMessage);
}

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

或者您可以自己创建这些:
final class CheckedSupplier implements Supplier {

private final SupplierThatThrows supplier;

CheckedSupplier(SupplierThatThrows supplier) {
this.supplier = supplier;
}

@Ghi đè
public T get() {
thử {
return supplier.get();
} catch (Throwable exception) {
throw new RuntimeException(exception);
}
}
}



@FunctionalInterface
interface SupplierThatThrows {

T get() throws Throwable;
}
和用法:
 CompletableFuture sad = CompletableFuture
.supplyAsync(new CheckedSupplier<>(SO64937499::throwSomething))
.exceptionally(Throwable::getMessage);

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

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com