Akka Futures Exceptions

What happens when a future actor throws an exception?

According to Akka's documentation at http://doc.akka.io/docs/akka/snapshot/scala/futures.html :

It does not matter if the actor or the dispatcher completes the Future, if the Exception is caught, the Future will contain this instead of the actual result. If Future contains an exception, calling Await.result will cause it to be thrown again so that it can be handled properly.

I'm not sure if this is what I see when I run 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 an exception again, but what I get is a TimeoutException! Can anyone clarify this?

+6
source share
1 answer

For actors, you need to catch the exception, and return it as a failure status . Right now, you are not returning anything to the sender, so you get 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 elegantly, as they always send the result, while the actors do not (this will give you the same result as above):

  val future = Future { throw new RuntimeException } 
+14
source

All Articles