Skip to content

ExceptionHandler Rules

Arif Yayalar (@ayayalar) edited this page Aug 24, 2018 · 3 revisions

The ExceptionHandler rule can react to unhandled exceptions of another rule. Set the IsExceptionHandler flag to true, specify a rule to listen using ObserveRule property. Can be very useful in rollback scenarios.

Must be set in 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 = typeof(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()

Clone this wiki locally