【问题标题】:Handling exceptions idiomatically with VAVR使用 VAVR 惯用地处理异常
【发布时间】:2020-04-29 07:35:19
【问题描述】:

从我们嘴里吐出 Google Guava Kool-aid,并一头扎进我们对 VAVR 及其闪亮理想的新迷恋中,假设我们是 map()ping 和 Stream,表演 foldLeft() Traversable 或类似的,并且其中一个内部函数引发检查异常。现在我们正盯着编译器错误、未处理的异常。

如何使用惯用的 VAVR 以理想方式处理此类异常。生成的代码是什么样的,模式是什么。我们有Options 和Trys...它们是如何结合在一起的。

哦,像偷偷摸摸的异常这样的技巧对我们不感兴趣。

【问题讨论】:

  • 基于值的Try 的好处是它需要您对这种处理做出决定。如果你的映射函数可以抛出,那么你希望你的结果是Try<Traversable<O>> 还是Traversable<Try<O>>?答案会告诉你如何包装。

标签: java vavr


【解决方案1】:

您可以使用CheckedFunction[0-8].liftTry() 将一个抛出检查异常的函数转换为一个总函数,该函数返回包装在Try 中的原始函数的结果。如果原始函数返回值没有抛出,它将被包裹在Success中,如果它抛出,异常将被包裹在Failure中。

然后,您需要决定如何处理多值上下文中的错误。下面是一些示例,说明您可以使用一堆 Try 值做什么。

Array<String> input = Array.of(
        "123", "456", "789", "not a number", "1111", "another non-number"
);

// try and parse all the strings
Array<Try<Integer>> trys = input.map(CheckedFunction1.liftTry(Integer::parseInt));

// you can take just the successful values
Array<Integer> values = trys.flatMap(Try::iterator);

// you can look just for the failures
Array<Throwable> failures = trys.filter(Try::isFailure).map(Try::getCause);

// you can partition by the outcome and extract values/errors
Tuple2<Traversable<Integer>, Traversable<Throwable>> partition =
    trys.partition(Try::isSuccess)
        .map(
            seq -> seq.map(Try::get),
            seq -> seq.map(Try::getCause)
        );

// you can do a short-circuiting parse of the original sequence
// this will stop at the first error and return it as a failure
// or take all success values and wrap them in a Seq wrapped in a Try
Try<Seq<Integer>> shortCircuit = Try.sequence(
    input.iterator() //iterator is lazy, so it's not fully evaluated if not needed
         .map(CheckedFunction1.liftTry(Integer::parseInt))
);
// Failure(java.lang.NumberFormatException: For input string: "not a number")

当然,您可以使用任何其他 vavr 集合来代替 Array

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多