Akka期货例外

dee*_*imo 6 scala exception-handling future exception akka

当未来的演员抛出异常时会发生什么?

根据http://doc.akka.io/docs/akka/snapshot/scala/futures.html上的Akka文档:

如果Actor或调度程序正在完成Future,则无关紧要,如果捕获到Exception,则Future将包含它而不是有效结果.如果Future确实包含Exception,则调用Await.result将导致它再次被抛出,以便可以正确处理它.

在运行这段代码时,我不确定这是我所看到的:

  class Worker extends Actor {
    def receive = {
      case i: Int => throw new RuntimeException
    }         
  }

  implicit val system = ActorSystem("MySystem")
  val worker = system.actorOf(Props(new Worker), name="worker")
  implicit val timeout = Timeout(5 minutes)
  val future = worker ? 0
  val res = Await.result(future, 10 seconds)
Run Code Online (Sandbox Code Playgroud)

根据文档,Await.result应该再次抛出异常,但我得到的是TimeoutException!有人可以澄清一下吗?

Noa*_*oah 15

对于actor,您需要捕获异常并将其作为失败状态返回.现在你没有向发件人返回任何东西,所以你得到一个超时异常:

class Worker extends Actor {
  def receive = {
    case i: Int => {
      try {
        throw new RuntimeException
        sender ! "Some good result"
      } catch {
        case e: Exception =>
          sender ! akka.actor.Status.Failure(e) // Alert the sender of the failure
          throw e // Alert any supervisor actor of the failure
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

期货可以更优雅地处理它,因为它们总是发送结果,而演员不会(这会给你与上面相同的结果):

  val future = Future {
    throw new RuntimeException
  }
Run Code Online (Sandbox Code Playgroud)