Search code examples
exceptionakkaactor

Is try catch in actors always bad practice?


I know excpetion handling in actors should in general be done with a supervisor strategy. But is this valid for all cases?

Example

  • There is one actor which is some kind of database.
  • There are several source actors which can add data to the database actor.
  • The parent child relationships of these actors are unknown.
  • To add data to the database actor the source actors must be registrated at the database actor.
  • If a not registrated source actors tries to add data to the database an exception is thrown.

If I follow the the error handling strategies of akka actors strictly, a supervising actor would have to handle this case.

I would prefer to catch the exception inside the database actor and send to the source actor a message, that something went wrong. Then the source actor could react (registrate to the database and try again).

Is this a good practice? Or is the total actor setup wrong? If a supervisor strategy is preferred, how should it be implemented?


Solution

  • It's perfectly fine to catch exceptions and make them into responses when you feel it's appropriate. I'd recommend using Scala's Try, as in:

    Try(dangerousOperation()) match {
      case Success(res) => sender() ! res
      case Failure(ex)  => sender() ! UnableToStoreThingy("reasons...", ex)
    }
    

    Or something like that (you can also try.failed.map { ex => doThings(ex) }), depends on your style preference.