如何创建一个可能抛出异常的akka​​ actor?

时间:2013-09-06 01:17:00

标签: scala akka actor

我正在将项目从scala actor迁移到akka actor。我曾经有类似这样的东西,如果某个系统资源不可用,MyActor的构造函数可能抛出异常:

var myActor: MyActor = null
try {
  myActor = new MyActor(3)
}
catch {
  case e: SomeUserDefinedException => println("failed!")
}

使用akka,我将代码迁移到了:

val someParam = 3
var myActor: ActorRef = null
try {
  myActor = context.actorOf(Props(classOf[MyActor], someParam), "myActor")
}
catch {
  case e: SomeUserDefinedException => println("failed!")
}

我遇到的问题是,似乎在akka情况下,context.actorOf调用实际上并不是创建MyActor对象本身,而是将其推迟到另一个线程。因此,当构造函数抛出异常时,我放入的try / catch块无效。

如何将此scala actor代码迁移到akka actor?理想情况下,我宁愿避免增加许多额外的复杂性。

1 个答案:

答案 0 :(得分:2)

您可以在MyActor的构造函数中捕获异常,并通知其他参与者(例如父级)有关此异常的信息。试试这个:

class MyActor(val parent: ActorRef) extends Actor {
  try{
    throw new RuntimeException("failed construct")
  } catch {
    case e: Throwable => 
        parent ! e
        throw e
  }

  def receive: Actor.Receive = {case _ => }
}

class ParentActor extends Actor {
  val child = context.actorOf(Props(classOf[MyActor], self), "child")
  override def receive = {
    case e: Throwable => println(e)
  }
}