我正在将一个项目从scala演员迁移到akka演员。我曾经有过这样的事情:如果某些系统资源不可用,MyActor的构造函数可能会引发异常:
I am migrating a project from scala actors to akka actors. I used to have something like this where the constructor of MyActor may throw an exception if a certain system resource is unavailable:
var myActor: MyActor = null try { myActor = new MyActor(3) } catch { case e: SomeUserDefinedException => println("failed!") }使用akka,我将代码迁移到了:
With akka, I migrated the code to this:
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 块无效。
The problem I'm having is that it seems like in the akka case, the context.actorOf call isn't actually creating the MyActor object itself, but deferring it to another thread. So when the constructor throws an exception, the try/catch block that I put in has no effect.
如何将这个Scala actor代码迁移到akka actor中?理想情况下,我希望避免增加很多额外的复杂性。
How can I migrate this scala actor code into akka actors? Ideally I would prefer to avoid adding a lot of additional complexity.
推荐答案您可以在 MyActor 并将此异常通知其他参与者(例如,父母)。试试这个:
You can catch the exception in the constructor of MyActor and notify other actors (e.g. the parent) about this exception. Try this:
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) } }更多推荐
应该如何创建可能引发异常的Akka演员?
发布评论