Akka期货例外 [英] Akka Futures Exceptions
问题描述
根据 http://doc.akka.io/docs/akka/snapshot/scala/futures.html :
如果一个Actor或调度程序正在完成
,那么没有关系未来,如果一个异常被捕获,Future将包含它,而不是
的有效结果。如果未来确实包含异常,调用
Await.result将导致它再次抛出,以便它可以正确处理
。
我不知道这是我运行这段代码时看到的:
class Worker扩展Actor {
def receive = {
case i:Int =>抛出新的RuntimeException
}
}
隐式val系统= ActorSystem(MySystem)
val worker = system.actorOf(Props(new Worker),name = worker)
implicit val timeout =超时(5分钟)
val future = worker? 0
val res = Await.result(未来,10秒)
根据文档Await.result应该再次抛出异常,但是我得到的是一个TimeoutException!有人可以澄清这一点吗?
对于演员,你需要捕获异常和将其作为失败状态返回。现在你没有给发件人返回任何东西,所以你得到一个超时异常:
class Worker extends Actor {
def receive = {
case i:Int => {
try {
throw new RuntimeException
sender! 一些好的结果
} catch {
case e:Exception =>
发件人! akka.actor.Status.Failure(e)//提醒失败的发件人
throw e //提醒任何失败的主管演员
}
}
}
}
期货可以更好地处理这一点,因为他们总是发送结果,而演员不(这会给你以上一样的结果):
val future = Future {
throw new RuntimeException
}
What happens when an actor of a future throws an exception?
According to the Akka documentation at 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.
I am not sure this is what I am seeing when running this piece of code:
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)
According to the documentation, Await.result should throw the exception again, but what I am getting is a TimeoutException! Can someone clarify on this?
For actors you need to catch the exception and return it as a failure status. Right now you're not returning anything to the sender so you're getting a timeout exception:
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 can handle this a little more gracefully since they always send a result, while actors do not (this would give you the same result as above):
val future = Future {
throw new RuntimeException
}
这篇关于Akka期货例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!