Scala恢复或恢复
发布时间:2020-12-16 09:29:13 所属栏目:安全 来源:网络整理
导读:我们正在Scala开发一些系统,我们有一些疑问.我们正在讨论如何映射未来的异常,我们不知道何时应该使用选项1或选项2. val created: Future[...] = ??? 选项1: ???? val a = created recover { case e: database.ADBException = logger.error("Failed ...",e)
|
我们正在Scala开发一些系统,我们有一些疑问.我们正在讨论如何映射未来的异常,我们不知道何时应该使用选项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] = {
恢复包装将来为你的未来(地图的模拟),而recoverWith期望Future作为结果(类似于flatMap). 所以,这里有经验法则: 如果您使用已返回Future的内容进行恢复,请使用recoverWith,否则请使用recover. UPD在您的情况下,首选使用recover,因为recover会将您的异常包装在Future中.否则没有性能增益或任何东西,所以你只需要避免一些样板. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
