映射失败的未来的例外 [英] Map the Exception of a failed Future
本文介绍了映射失败的未来的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
映射
失败的未来$的
异常
的最干净的方法是什么? c $ c>在scala中?
What's the cleanest way to map
the Exception
of a failed Future
in 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")
}
如果Future成功且 1
,我想保留,但是如果失败,我想将 Exception
更改为另一个 Exception
。
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))
是否有任何原因没有 mapFailure(PartialFunction [Throwable ,Throwable])
?
推荐答案
还有:
f recover { case cause => throw new Exception("Something went wrong", cause) }
从Scala 2.12开始,您可以执行以下操作:
Since Scala 2.12 you can do:
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)))}
这篇关于映射失败的未来的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文