【问题标题】:Handle exception of the Await.result from Scala Future处理来自 Scala Future 的 Await.result 异常
【发布时间】:2018-06-15 19:24:07
【问题描述】:

我对 Scala 有一个理解,我想处理 Await.result 的异常。问题是我的捕获显示None.get,但不是我定义的异常。

异常在case e: Exception => BadRequest(s"Exception found: ${e.getMessage}") 被捕获,但它是一个Future。我想显示 getMessage。

try {
  val futureResult = for {
    futureRackRow <- rackRepository.getById(rack.id) recoverWith {
      case e: Exception => throw RackException(s"Error on select Rack: ${e.getMessage}")
    }
    futureSeqGpuRow <- gpuRepository.getByRack(futureRackRow.get.id) recoverWith {
      case e: Exception => throw GpuException(s"Error on select Gpu's from Rack: ${e.getMessage}")
    }
  } yield (futureRackRow, futureSeqGpuRow)
  println(2)
  val result = Await.result(futureResult, 20 seconds) // The exception comes here ....

  result._1 match {
    case Some(rackRow) => ???
    case None => ???
  }
  Ok
} catch {
  case re: RackException => BadRequest(s"Rack Exception: ${re.getMessage}")
  case ge: GpuException => BadRequest(s"Gpu Exception: ${ge.getMessage}")
  case e: Exception => BadRequest(s"Exception found: ${e.getMessage}")
}

【问题讨论】:

  • 您发布的代码没有Option.get,因此不清楚如何获得None.get 异常

标签: scala exception future


【解决方案1】:

我假设您遇到None.get 的例外情况是futureRackRow 在这里是None。然后在调用 getByRack 之前,它会抛出一个异常来调用.id。因此它与期货无关:)

最好在阻塞之前抓住它,比如

if (futureRackRow.nonEmpty) {
  ...
}

或者如果你有一些默认值,你可以使用它来代替 .get.id

 futureRackRow.map(_.id).getOrElse(0)

【讨论】:

  • 我不能在内部使用 isEmpty 来获得 {} 并抛出异常。我在 Await.result 之后写的所有东西都不会被执行。我的例外是在rackRepository.getById(rack.id) 内部,但是throw RackException 没有被执行......
  • 你怎么知道异常在rackRepository.getById(rack.id)?我不这么认为。您需要处理选项futureRackRowNone 的情况,因此我的意思是用.isEmpty 包装您的整个代码,或者使用默认值(如果可用)。
  • 我在最后放了一个 NonSushElementException 来解决这个问题。我仍然无法获得特定的异常,也无法在 for{} 周围使用 isEmpty。这是我的实现github.com/felipegutierrez/crypto-miners-demo/blob/master/app/… 如果你能给我一个你想法的例子,那也很好。谢谢
  • 我也想知道是否可以从我的代码中删除Await.result(futureResult, 20 seconds)....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
相关资源
最近更新 更多