Search code examples
actorakka.netakka-supervision

Akka.net - additional error handling by coordinator


Given an Akka.net-based actor system with some basic structure like:

/user
  /coordinator
    /child (x1000, with RoundRobinPool router)

Coordinator actor defines supervision strategy with Directive.Restart used.

Child actors could fail for several reasons (for example, with ArithmeticException, InvalidOperationException and MyCustomException).

But when a child fails with MyCustomException, I'd like to have an ability to somehow additionally handle it without changing the default supervision mechanism (restart approach should still work here). For example, to add Console.Writeline with exception details.

How do I implement it?


Solution

  • In general MyCustomException signals, that you're in charge when the exception occurs, and you could log it right away in your child logic, without need to elevating it to parent. But if it's not possible you can define your own supervisor strategy class like this:

    public class MySupervisorStrategy : OneForOneStrategy
    {
        public MySupervisorStrategy(ILoggingAdapter log) : base(reason =>
            {
                if (reason is MyCustomException)
                {
                    log.Error(reason.Message);
                    return Directive.Restart;
                }
    
                return Akka.Actor.SupervisorStrategy.DefaultDecider.Decide(reason);
            })
        {
        }
    }
    

    There are two ways how to apply it to your actor:

    1. Use Props.Create<MyActor>().WithSupervisorStrategy(new MySupervisorStrategy(system.Log) to apply it directly from your actor system.
    2. Attach it directly in actor's logic by overriding SupervisorStrategy method of an actor (use Context.GetLogger() to receive log instance for current actor).

    Second option is less flexible but will probably work better in situations where you need to use remote deployment scenarios.