捕获Future.failed错误

时间:2018-03-07 03:25:32

标签: scala

以下代码打印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)
}

1 个答案:

答案 0 :(得分:3)

您的futureFunction将始终返回Future{2}。以下内容可能满足您的需求:

def futureFunction (i: Int) = {
  if (i==1) 
    Future.failed(new Throwable("error msg"))
  else
    Future.successful(2)
}