以下函数调用一个actor:
def read () = {
val system = ActorSystem(Constant.actorSystem)
val manageData = system.actorOf(Props[ManageData], name = "theactor")
val num = -1
implicit val timeout = Timeout(60 seconds)
val future = manageData ? num
val result = Await.result(future, timeout.duration)
}
在manageData
内,子进程抛出异常:
throw new Exception("Negative number")
如何在read()
中抓住它?
答案 0 :(得分:0)
这是一个老问题,但是我不得不处理它。
如果异常是我不期待的,我通常会在演员主管上对待它:
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException => {
log.error("\n# ArithmeticException -> Resume\n")
Resume
}
// other exceptions
}
}
对于其他类型的错误,我倾向于回复错误并在以下情况下处理:
case class IError(code:Int, msg:Option[String] = None)
sender ! IError(401, msg= Some("Unauthorized"))