【问题标题】:Catching an exception as a response of an actor in Akka在 Akka 中捕捉异常作为演员的响应
【发布时间】:2016-06-13 17:43:44
【问题描述】:

以下函数调用一个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() 中捕获它?

【问题讨论】:

  • 抛出异常将重启actor,创建父actor并在子actor中完成所有工作,并通过覆盖其监督策略来处理子actor在其父actor中抛出的异常。
  • 那么将错误从参与者返回给调用者的最佳做法是什么?
  • 要么通过向发送者发送消息将信息传递给发送者,要么在此actor的父级中处理此异常并相应地对其进行监督。
  • 我只是扩展@curious 的评论,如果错误是意外的——比如运行时异常——应该在父母的监督策略中处理。但如果错误具有业务语义,它很可能不是错误或异常,应作为消息发送回sender()

标签: scala akka


【解决方案1】:

这是一个老问题,但我放弃了处理它的方式。

如果异常是我没有预料到的,我通常会在演员主管身上处理它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多