Search code examples
scalaakkaactor

How to catch the exceptions thrown inside an actor?


In my actor, the methods may throw exception:

class ServerActor extends Actor {
  override def receive: Receive = {
    case "Start" =>
      println("### actor started")
      throw new Exception("My exception when starting")
    case msg =>
      println("### actor get other message: " + msg)
      throw new Exception("another exception for other messages: " + msg)
  }
}

Is there any way to handle all the exception in a single place? I want to handle them together, e.g. logging them


Solution

  • Well you can try to do this in parent under supervision strategy: http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html

    Or you have this method on actor:

    def preRestart(reason: Throwable, message: Option[Any]): Unit

    where reason is the exception that caused the actor to crash.