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])
?
答案 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))
}