I have my drools server configured via spring/camel and I'd like to be able log to a file all runtime exceptions that occur when rules are fired, along with details about the state of the working memory at the time of the exception.
I found that drools version >= 5.2 of drools-spring does allow for the setting of a custom ConsequenceExceptionHandler class in the spring configuration:
https://issues.jboss.org/browse/JBRULES-2674
I'm having some trouble (some of which related from migrating from drools 5.1 to 5.2) so I was wondering if anyone has done the logging of exceptions before and could share some implementation details. Or if someone can tell me if there's a better way to achieve this than through a c开发者_如何学编程ustom exception handler.
In my project (I think I'll have to write about it on my blog http://toomuchcoding.blogspot.com where I have some articles about Drools) I wrote a custom Listener in the following manner (I think I found a nice tutorial over here http://members.inode.at/w.laun/drools/CustomConsequenceExceptionHandlingHowTo.html)
I defined my KnowledgeBase as a bean in my applicationContext:
<drools:kbase id="fxKBase">
<drools:resources>
<drools:resource type="DRL" source="classpath:path/first.drl"/>
<drools:resource type="DRL" source="classpath:path/second.drl"/>
</drools:resources>
<drools:configuration>
<drools:consequenceExceptionHandler handler="a.b.c.MyConsequenceExceptionHandler" />
</drools:configuration>
</drools:kbase>
Then I defined MyConsequenceExceptionHandler
public class MyConsequenceExceptionHandler implements ConsequenceExceptionHandler {
@Override
public void handleException(Activation activation, WorkingMemory workingMemory, Exception exception) {
throw new MyConsequenceException(activation, workingMemory, exception);
}
and the MyConsequenceException:
public class MyConsequenceException extends RuntimeException {
private final WorkingMemory workingMemory;
private final Activation activation;
public MyConsequenceException(final Activation activation, final WorkingMemory workingMemory, final Exception exception) {
super(exception);
this.activation = activation;
this.workingMemory = workingMemory;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder( "Exception executing consequence for " );
if( activation != null && ( activation.getRule() ) != null ){
Rule rule = activation.getRule();
String ruleName = rule.getName();
sb.append("rule [\"").append( ruleName ).append( "\"]. " );
} else {
sb.append( "rule, name unknown" );
}
Throwable throwable = ExceptionUtils.getRootCause(getCause());
sb.append("The thrown exception is [").append(throwable).append("]. ");
return sb.toString();
}
@Override
public String toString() {
return getMessage();
}
}
In that way when an exception is thrown you will get a custom message of your choosing.
精彩评论