Capturing an exception as an actor’s response in Akka

The following function calls the 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)
}

Inside the manageDatachild process throws an exception:

throw new Exception("Negative number")

how to catch him in read()?

+4
source share
1 answer

This is an old question, but I leave my way to deal with it.

If an exception is what I do not expect, I usually relate to it above the actor’s leader:

override val supervisorStrategy =
  OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
    case _: ArithmeticException      => {
      log.error("\n# ArithmeticException -> Resume\n")
      Resume
    }
    // other exceptions
  }
}

For other types of errors, I tend to respond to the error and solve it after:

case class IError(code:Int, msg:Option[String] = None)

sender ! IError(401, msg= Some("Unauthorized"))
0
source

All Articles