exception handler in drools rule

As I know, we have 2 ways to handle exception in drools rule:

1.  try-catch in rule file(.drl) consequence:

 e.g.

rule "r1"

when
//conditions
then
try{
//do something...
}catch(Exception e){
//exception handler
}

end


2. create your own exception handler class implement  ConsequenceExceptionHandler, register it to knowledgebase

e.g:

public StatefulKnowledgeSession getSession() {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(fileName,
TestListObjOnlyRunOnce.class), ResourceType.DRL);


if (kbuilder.hasErrors()) {
System.out.println("規則錯誤:");
Iterator<KnowledgeBuilderError> it = kbuilder.getErrors()
.iterator();
while (it.hasNext())
System.out.println(it.next());
return null;
}
KnowledgeBaseConfiguration kBaseConfig =
           KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
       @SuppressWarnings("unchecked")
       Class ehClass = MyConsequenceExceptionHandler.class;
       ConsequenceExceptionHandlerOption cehOption = ConsequenceExceptionHandlerOption.get( ehClass );
       kBaseConfig.setOption( cehOption );

       
       KnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase(kBaseConfig);
kb.addKnowledgePackages(kbuilder.getKnowledgePackages());
return kb.newStatefulKnowledgeSession();
}

-----exception handler class---

package com.test.DroolsRuleTests;


import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;


import org.drools.runtime.rule.Activation;
import org.drools.runtime.rule.ConsequenceExceptionHandler;
import org.drools.runtime.rule.WorkingMemory;


public class MyConsequenceExceptionHandler implements ConsequenceExceptionHandler, Externalizable {



    public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {}
    public void writeExternal( ObjectOutput out ) throws IOException {}


    public void handleException( Activation activation,
                                 WorkingMemory workingMemory,
                                 Exception exception ){

// exception handler logic here
    System.err.println("excpeiton occured when execute rule: " + activation.getRule().getName());
    XXX  xxx =(XXX) workingMemory.getObject(activation.getPropagationContext().getFactHandle());
    exception.printStackTrace();
    }
}

發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章