当 future 的参与者抛出异常时会发生什么?
根据 Akka 文档 http://doc.akka.io/docs/akka/snapshot/scala/futures.html :
It doesn't matter if an Actor or the dispatcher is completing the Future, if an Exception is caught the Future will contain it instead of a valid result. If a Future does contain an Exception, calling Await.result will cause it to be thrown again so it can be handled properly.
我不确定这就是我在运行这段代码时所看到的:
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)
根据文档,Await.result应该再次抛出异常,但我得到的是TimeoutException!有人可以澄清一下吗?
最佳答案
对于 Actor ,您需要捕获异常并 return it as a failure status 。现在您没有向发件人返回任何内容,因此您遇到了超时异常:
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
}
}
}
}
Futures 可以更优雅地处理这个问题,因为它们总是发送结果,而 actor 则不会(这会给你与上面相同的结果):
val future = Future {
throw new RuntimeException
}
关于scala - Akka future 异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095462/