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

How to catch the exceptions thrown inside an 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)
  }
}

有什么方法可以在一个地方处理所有的异常吗?我想一起处理它们,例如记录它们

那么你可以在监督策略下尝试在家长中这样做: http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html

或者你在 actor 上有这个方法:

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

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