Skip to content

ExceptionHandler Rules

Arif Yayalar (@ayayalar) edited this page Dec 30, 2019 · 3 revisions

An ExceptionHandler rule can react to unhandled exceptions of another rule. Set the IsExceptionHandler flag to true, specify a rule to listen using ObserveRule property. It can be instrumental in rollback scenarios.

Must be set in the Initialize method.
Example

In the following example HandleUpdateShippingException is an ExceptionHandler Rule. It gets invoked only if UpdateShipping rule throws exception.

class UpdateShipping : Rule<Order>
{
    public override IRuleResult Invoke()
    {
        throw new Exception();
    }
}
class HandleUpdateShippingException : Rule<Order>
{
    public override void Initialize()
    {
        // Flag rule to be an exception handler
        IsExceptionHandler = true;

        // Specify rule to monitor for exceptions.
        ObserveRule<UpdateShipping>();
    }

    public override IRuleResult Invoke()
    {
        // Exception from the UpdateShipping rule gets assigned to the UnhandledException property.
        if (UnhandledException.GetType() == typeof(Exception)
        {
            // Handle exception.
        }
        return null;
    }
}

Invoke Rule(s)

var ruleResults = await RuleEngine<Order>.GetInstance(order)
    .ApplyRules(new UpdateShipping(), new HandleUpdateShippingException())
    .Execute()