【问题标题】:Is there a better way to log failures in a chain of Java Vavr Try clauses?有没有更好的方法在 Java Vavr Try 子句链中记录失败?
【发布时间】:2019-02-02 09:31:10
【问题描述】:

我正在尝试在每个失败阶段进行记录,据我所知,我需要将 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 的函数?

【问题讨论】:

    标签: java try-catch fluent flatmap vavr


    【解决方案1】:

    为什么要嵌套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")));
    

    【讨论】:

    • 如果我正确阅读了你写的内容,如果 of() '抛出',那么这将记录 3 次,我不想这样做
    • 我的错。那我觉得不可能。除非您愿意在平面图之后的 onFailure 中一劳永逸地进行某种模式匹配(例如使用 recover),否则您的工作流程在出现错误时不是线性短路(而平面图对此很有用)。
    【解决方案2】:

    如果你只想记录失败,你可以做一次:

    Try.of(() -> method1())
            .mapTry(i -> method2())
            .mapTry(k -> method3())
            .onFailure(throwable -> log.error("Something wrong", throwable));
    

    【讨论】:

    • 谢谢,但我希望能够记录每个子条款的失败,而不是整个语句
    • @RichardPolton 刚刚编辑了答案。正如我所看到的,异常的堆栈跟踪可以显示哪个子条款失败。但是如果你想要更多的控制,你应该使用嵌套的 Try.of()
    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多