映射失败的未来的例外

时间:2013-08-15 10:32:08

标签: scala akka future scala-2.10

scala中map Exception Future的最简洁方法是什么?

说我有:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

val f = Future { 
  if(math.random < 0.5) 1 else throw new Exception("Oh no") 
}

如果未来以1成功,我想保留,但如果失败,我想将Exception更改为其他Exception

我能想到的最好的就是改造,但这需要我为成功案例制定一个不必要的功能:

val f2 = f.transform(s => s, cause => new Exception("Something went wrong", cause))

是否有任何理由没有mapFailure(PartialFunction[Throwable,Throwable])

2 个答案:

答案 0 :(得分:34)

还有:

f recover { case cause => throw new Exception("Something went wrong", cause) }

从Scala 2.12开始,你可以这样做:

f transform {
  case s @ Success(_) => s
  case Failure(cause) => Failure(new Exception("Something went wrong", cause))
}

f transform { _.transform(Success(_), cause => Failure(new Exception("Something went wrong", cause)))}

答案 1 :(得分:15)

您可以尝试recoverWith,如下所示:

f recoverWith{
  case ex:Exception => Future.failed(new Exception("foo", ex))
}