scala 映射失败的 Future 的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18250888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:35:09  来源:igfitidea点击:

Map the Exception of a failed Future

scalaakkafuturescala-2.10

提问by theon

What's the cleanest way to mapthe Exceptionof a failed Futurein scala?

什么是最干净的方式mapException的失败Future在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 Exceptionto a different Exception.

如果 Future 成功1,我想保留它,但是如果它失败了,我想将 更改Exception为不同的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])?

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

回答by Viktor Klang

There is also:

还有:

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

Since Scala 2.12 you can do:

从 Scala 2.12 开始,您可以执行以下操作:

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)))}

回答by cmbaxter

You could try recoverWithas in:

您可以尝试recoverWith如下:

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