Kirill G.
Kirill G.

Reputation: 960

Serialization of Try/Success/Failure in Scala Akka

I am trying to ask an actor which would reply with a Try:

val reply = actor.ask[Try[MyReply]](MyCommand)

However when reply comes from an actor on another node in the cluster I get following error in logs:

Failed to serialize message [scala.util.Success].

Interestingly enough, if I use Option instead of Try things seem to work fine. I want to use Try for better errors control. Is there a way to achieve this with a Try?

Upvotes: 0

Views: 451

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

I think this is done on purpose by developers of akka to avoid usage of Try as transfer types.

Try is designed to handle all non fatal exceptions. And this will require you to serialise exceptions so they are to be transferred over network and handled on other node. Imo, an exception must be handled locally.

If you wish to transfer your business errors, I'd suggest to use Either[MyError, MyReply] instead, where MyError can be your own case class defining specific business errors.

Edit:

As @artur suggested, you can also use akka.pattern.StatusReply to notify back error messages.

case class Command(replyTo: ActorRef[StatusReply[MyReply]])

val actorRef: ActorRef[Command] = ???
actorRef.askWithStatus(Command).onComplete {
  case Success(response) =>
  case Failure(StatusReply.ErrorMessage(text)) => ???
  case Failure(_) => ???
}

Upvotes: 2

Related Questions