如何捕捉演员内部抛出的异常?

时间:2015-10-07 04:50:48

标签: scala akka actor

在我的演员中,方法可能会抛出异常:

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)
  }
}

有没有办法在一个地方处理所有异常?我想一起处理它们,例如记录它们

1 个答案:

答案 0 :(得分:5)

你可以在监督策略下尝试在父母那里做到这一点: http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html

或者你对actor有这个方法 def preRestart(reason: Throwable, message: Option[Any]): Unit

其中reason是导致actor崩溃的异常。