有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java CompletableFuture句柄和CompleteException不能一起工作吗?

CompletableFuture中发生异常时,我试图设置一个默认值。我通过handle方法使其工作如下:

private static void testHandle() {
    String name = null;
    CompletableFuture<String> completableFuture
            = CompletableFuture.supplyAsync(() -> {
        if (name == null) {
            throw new RuntimeException("Computation error!");
        }
        return "Hello, " + name;
    }).handle((s, t) -> s != null ? s : "Hello, Stranger!" + t.toString());
    out.println(completableFuture.join());
}

但是,当我试图在坏事情发生时使用completeExceptionally停止CompletableFuture,并按如下方式跟踪异常时,我无法像刚才那样捕捉异常

private static void testCompleteExceptionally() {
    String name = "Hearen";
    CompletableFuture<String> completableFuture
            = CompletableFuture.supplyAsync(() -> {
        delay(500L);
        if (name == null) {
            throw new RuntimeException("Computation error!");
        }
        return "Hello, " + name;
    }).handle((s, t) -> {
        try {
            throw t.getCause(); 
        } catch (Throwable e) {
            out.println(e.toString()); // I was hoping to record the custom exceptions here;
        }
        return s != null ? s : "Hello, Stranger!" + t.toString();
    });

    if (name != null) {
        completableFuture.completeExceptionally(new RuntimeException("Calculation failed!")); // when bad things happen, I try to complete it by exception;
    }
    out.println(completableFuture.join());

}

更新2018-06-09谢谢你的帮助,@Daniele

private static void testCompleteExceptionally() {
    String name = "Hearen";
    CompletableFuture<String> completableFuture
            = CompletableFuture.supplyAsync(() -> {
        delay(500L);
        if (name == null) {
            throw new RuntimeException("Computation error!");
        }
        return "Hello, " + name;
    });

    if (name != null) {
        completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
    }
    out.println(completableFuture.handle((s, t) ->  s != null ? s : "Hello, Stranger!" + t.toString()).join());

}

就在join()之前的句柄按预期工作。但是在这种情况下,returned value将是null

基于handle API

Returns a new CompletionStage that, when this stage completes either normally or exceptionally, is executed with this stage's result and exception as arguments to the supplied function.


共 (0) 个答案