把 Google Guava kool-aid 从我们嘴里吐了出来,并一头扎进我们对 VAVR 及其闪闪发光的理想的新迷恋中,假设我们正在 map()
ping Stream
,在 Traversable
上执行 foldLeft()
或类似的操作,并且内部函数之一会引发已检查的异常。现在我们正盯着编译器错误、未处理的异常。
如何使用惯用的 VAVR 来理想地处理此类异常。结果代码是什么样的,有什么模式。我们有选项
和尝试
...这一切是如何结合在一起的。
哦,像偷偷摸摸的异常(exception)这样的技巧我们不感兴趣。
最佳答案
您可以使用 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
。
关于java - 使用 VAVR 惯用方式处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61496512/