Map the Exception of a failed Future

☆樱花仙子☆ 提交于 2019-12-03 06:34:37

问题


What's the cleanest way to map the Exception of a failed Future in scala?

Say I have:

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

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

If the Future succeeds with 1, I'd like to keep that, however if it fails I would like to change the Exception to a different Exception.

The best I could come up with is transform, however that requires me to make a needless function for the success case:

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

Is there any reason there is no mapFailure(PartialFunction[Throwable,Throwable])?


回答1:


There is also:

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

Since Scala 2.12 you can do:

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

or

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



回答2:


You could try recoverWith as in:

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


来源:https://stackoverflow.com/questions/18250888/map-the-exception-of-a-failed-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!