应该如何创建可能引发异常的Akka演员? [英] How should an akka actor be created that might throw an exception?

查看:71
本文介绍了应该如何创建可能引发异常的Akka演员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个项目从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.

推荐答案

您可以在<$ c的构造函数中捕获异常$ c> 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演员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆