以下代码打印2
,但我希望(错误地)Future.failed
充当Java throw new Exception
,停止任何后续指令(并由recover
捕获)。如何使此代码打印“错误消息”?
object HelloScala extends App {
val f = futureFunction(1)
f.map { result => println(result) }
.recover { case e => println(e.getMessage) }
def futureFunction (i:Int) = {
if (i==1)
Future.failed(new Throwable("error msg"))
Future {2}
}
Thread.sleep(10000)
}
答案 0 :(得分:3)
您的futureFunction
将始终返回Future{2}
。以下内容可能满足您的需求:
def futureFunction (i: Int) = {
if (i==1)
Future.failed(new Throwable("error msg"))
else
Future.successful(2)
}