38

scala中失败的最干净的方法是map什么?ExceptionFuture

说我有:

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

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

如果 Future 成功了1,我想保留它,但是如果它失败了,我想将它更改Exception为不同的Exception.

我能想到的最好的方法是转换,但这需要我为成功案例创建一个不必要的函数:

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

有什么理由没有mapFailure(PartialFunction[Throwable,Throwable])吗?

4

2 回答 2

42

还有:

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)))}
于 2013-08-15T12:39:10.033 回答
16

您可以尝试recoverWith如下:

f recoverWith{
  case ex:Exception => Future.failed(new Exception("foo", ex))
}
于 2013-08-15T10:47:17.043 回答