1

我试图在每个失败阶段记录,据我所知,我需要将 try 和 log 嵌套在平面图中。

Try.of(() -> true).
    onFailure(h -> System.out.println("first onFailure")).
    flatMap(i -> Try.of(() -> { throw new RuntimeException(); }).
                     onFailure(j -> System.out.println("second onFailure"))).
    flatMap(k -> Try.of(() -> true).
                     onFailure(l -> System.out.println("third onFailure")));

有没有比上述更简单的方法?库中是否有可用于替换嵌套Try.of()s 的函数?

4

2 回答 2

0

为什么要嵌套onFailure调用?这个语法怎么样?

Try.of(() -> true)
        .onFailure(h -> System.out.println("first onFailure"))
        .flatMap(i -> Try.of(() -> { throw new RuntimeException(); }))
        .onFailure(j -> System.out.println("second onFailure"))
        .flatMap(k -> Try.of(() -> true)
        .onFailure(l -> System.out.println("third onFailure")));
于 2018-08-27T23:02:55.027 回答
0

如果您只想记录失败,则可以执行一次:

Try.of(() -> method1())
        .mapTry(i -> method2())
        .mapTry(k -> method3())
        .onFailure(throwable -> log.error("Something wrong", throwable));
于 2018-08-28T07:43:46.317 回答