应该如何创建可能引发异常的Akka演员?

编程入门 行业动态 更新时间:2024-10-22 16:28:52
本文介绍了应该如何创建可能引发异常的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.

推荐答案

您可以在 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演员?

本文发布于:2023-11-25 02:58:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628039.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   演员   Akka

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!