Search code examples
javadrools

Exception handling at individual rule level - Drools


How to catch and handle exceptions at individual rule level in Drools?

Aim is that exceptions at a single rule should not impact the execution of the rest of the rules.

I know that we can use try catch in RHS, but can we have a control at much higher level irrespective of what LHS or RHS is.

Something like:

fireAllRules( new DefaultAgendaEventListener() {
    @Override
        public void whenExceptionAtRule(Exception exception) {
            //handle exception when 
        }
})

Solution

  • First, you need to implement the org.kie.api.runtime.rule.ConsequenceExceptionHandler interface:

    package sample;
    
    public class MyConsequenceExceptionHandler implements ConsequenceExceptionHandler {
    
        @Override
        public void handleException(Match match, RuleRuntime rr, Exception excptn) {
            //Do whatever you want
        }
    
    }
    

    Then, it all depends on how are you creating your KieBases. If you are doing it manually (without using a kmodule.xml file), then you need to create a KieBaseConfiguration to specify what class you want to use to handle exceptions:

    KieBaseConfiguration kconfig = new RuleBaseConfiguration();
    kconfig.setProperty(ConsequenceExceptionHandlerOption.PROPERTY_NAME, "sample.MyConsequenceExceptionHandler");
    

    And then use this kconfig object when creating your KieBase:

    KieSession ksession = kcontainer.newKieBase(kconfig).newKieSession();
    

    I couldn't find a declarative way to register the handler in the kmodule.xml file though.

    Hope it helps,