gpt4 book ai didi

Scala 恢复或recoverWith

转载 作者:行者123 更新时间:2023-12-04 22:45:05 25 4
gpt4 key购买 nike

我们公司正在 Scala 开发一些系统,我们有一些疑问。我们正在讨论如何映射 future 的异常,我们不知道什么时候应该使用选项 1 或选项 2。

val created: Future[...] = ???

选项1:

val a = created recover {   
case e: database.ADBException =>
logger.error("Failed ...", e)
throw new business.ABusinessException("Failed ...", e)
}

选项 2:
val a = created recoverWith {   
case e: database.ADBException =>
logger.error("Failed ...", e)
Future.failed(new business.ABusinessException("Failed ...", e))
}

有人可以解释我什么时候应该做选项 1 或选项 2 吗?区别是什么?

最佳答案

好吧,scaladocs 中清楚地描述了答案:

  /** Creates a new future that will handle any matching throwable that this
* future might contain. If there is no match, or if this future contains
* a valid result then the new future will contain the same.
*
* Example:
*
* {{{
* Future (6 / 0) recover { case e: ArithmeticException => 0 } // result: 0
* Future (6 / 0) recover { case e: NotFoundException => 0 } // result: exception
* Future (6 / 2) recover { case e: ArithmeticException => 0 } // result: 3
* }}}
*/
def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U] = {

/** Creates a new future that will handle any matching throwable that this
* future might contain by assigning it a value of another future.
*
* If there is no match, or if this future contains
* a valid result then the new future will contain the same result.
*
* Example:
*
* {{{
* val f = Future { Int.MaxValue }
* Future (6 / 0) recoverWith { case e: ArithmeticException => f } // result: Int.MaxValue
* }}}
*/
def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U] = {
recoverFuture 中包装简单的结果为你( map 的模拟),而 recoverWith预计 Future结果( flatMap 的模拟)。

所以,这是经验法则:

如果你用已经返回的东西恢复 Future , 使用 recoverWith ,否则使用 recover .

更新
在您的情况下,使用 recover是首选,因为它将异常包装在 Future 中为你。否则没有性能提升或任何东西,所以你只需避免一些样板。

关于Scala 恢复或recoverWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com