Scala - Difference between Supervisor and Try-catch error handling strategies

141 Views Asked by At

can someone explain the difference between the "supervisor"- and the "try-catch"-error handling strategies in an ActorSystem in Scala?

1

There are 1 best solutions below

0
On BEST ANSWER

Try-catch can recover from Exception thrown within the try block (provided that error is reported by throwing Exception). It isn't tied to actors but it's an available method of dealing with errors in Scala (inherited from Java):

def method(arg: String): Int = try {
  arg.toInt
} catch {
  case _: Throwable => 0
}

Supervisor is used to decide what to do if Exception in our code wasn't caught or if some other error happened - which usually means some other Exception but not thrown nor handled by our code - transporting message from one cluster to another, invalid internal state, etc.

Try-catch is something you can use inside your own code to make sure that a method will succeed. It's very local in scope. If you cannot make such guarantee and want to tell ActorSystem what to do with an Actor that couldn't handle error on its own (or maybe even with a whole group of Actors) then you use Supervisor - Supervisor however cannot just catch Exception and make sure that function will return normal value instead. It will order Actor to restart (with clearing its state or with keeping the current state), kill Actor permanently or escalate to Actor's parent.

When supervision is needed is quite well explained in the documentation.

Simplifying, dealing with errors on processing should be left for Actor, which internaly recovers from errors using try-catch, Try, etc, while Supervisor should be used with SupervisionStrategies to provide fault-tolerance like in documentation.