我们公司正在用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] = {
recover
将普通结果包装在Future
为你(类似map
), 尽管recoverWith
期望Future
结果(模拟flatMap
).
所以,这是经验法则:
如果你恢复了已经返回的东西Future
, use recoverWith
,否则使用recover
.
update在你的情况下,使用recover
是首选,因为它将异常包装在Future
为你。否则不会有任何性能提升或任何东西,所以你只是避免一些样板。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)