映射失败的未来的例外

the*_*eon 31 scala future akka scala-2.10

什么是最干净的方式mapException的失败Future在Scala呢?

说我有:

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

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

如果未来成功1,我想保留它,但是如果它失败了我想改变Exception到另一个Exception.

我能想出的最好的是变换,但是这需要我为成功案例制定一个不必要的功能:

val f2 = f.transform(s => s, cause => new Exception("Something went wrong", cause))
Run Code Online (Sandbox Code Playgroud)

有没有理由没有mapFailure(PartialFunction[Throwable,Throwable])

Vik*_*ang 35

还有:

f recover { case cause => throw new Exception("Something went wrong", cause) }
Run Code Online (Sandbox Code Playgroud)

从Scala 2.12开始,您可以:

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

要么

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

  • 虽然这是一个非常清晰的语法,但我们仍然必须“抛出”新的异常,而不是将“Throwable”映射到“Throwable”。是否有一个组合器? (2认同)

cmb*_*ter 15

您可以尝试recoverWith:

f recoverWith{
  case ex:Exception => Future.failed(new Exception("foo", ex))
}
Run Code Online (Sandbox Code Playgroud)