简体   繁体   English

从Scala Future处理Await.result的异常

[英]Handle exception of the Await.result from Scala Future

I have a for comprehension in Scala and I want to handle an Exception of the Await.result. 我在Scala中有一个理解力,我想处理Await.result的异常。 The problem is that my catch shows None.get , but not my exception that I defined. 问题是我的捕获显示了None.get ,但是没有显示我定义的异常。

The exception is caught at case e: Exception => BadRequest(s"Exception found: ${e.getMessage}") but it is a Future. case e: Exception => BadRequest(s"Exception found: ${e.getMessage}")捕获到case e: Exception => BadRequest(s"Exception found: ${e.getMessage}")但这是一个Future。 I would like to show the getMessage. 我想展示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}")
}

I'd assume you get the exception with None.get is that the futureRackRow is None here. 我以为您会收到None.get的异常,就是futureRackRow在此处为None Then before even calling getByRack it will throw an Exception for calling .id on it. 然后,甚至在调用getByRack之前,它将在调用.id时引发异常。 Thus it has nothing to do with the Futures :) 因此,它与期货无关:)

Best catch it before the block, like 最好在块之前抓住它,就像

if (futureRackRow.nonEmpty) {
  ...
}

or if you have some default value you could use this instead of the .get.id 或者,如果您有一些默认值,则可以使用它代替.get.id

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM