问题
How do we handle exceptions in Drools files?
Example: My rule uses a shared Java method.
rule "002.17.1"
dialect "mvel"
when
comp : Component()
then
boolean validstate = SharedCodeUtil.hasValidateStateCountryUS(comp.address);
errors.add(new ValidationFailure("002.17.1", comp.getSubApplicationGroupID(), comp.getSubApplicationID(),tokens));
end
Java method SharedCodeUtil, may have exceptions:
if (m != null)
{
try
{
Object o = m.invoke(form,(Object[])null);
if(BudgetType.Project.equals(o))
count++;
}
catch (Exception e)
{
LOG.error("Error", e);
// re-throw? who will catch?
}
There's an Exception condition in the shared Java method called by the Drools file. Who is going to catch it, and what else should I do besides logging it?
回答1:
There is no particular problem with catching exceptions on the right hand side of a rule: this is Java code.
when
//...
then
try { /* some code */
} catch( SomeException ex ){ /* handle ex */ }
end
Whether you need to re-throw is a design decision, depending on the kind of exception. If reflection goes wrong, you have a fundamental problem in the code, and continuation is very likely pointless. If you rethrow, the next level is where the rule engine is called:
try {
kSession.fireAllRules();
} catch( Exception e ){
//... handle exception
}
You'll probably have to terminate the application after logging a severe error.
The situation is different when exceptions are thrown in code that is executed during rule evaluation. This cannot be caught "inside", and it will unwind to a handler around fireAllRules.
Note that negative validation results should better not be propagated via exceptions.
来源:https://stackoverflow.com/questions/28481600/handling-exceptions-in-drools-files