我在 JEXL 引擎中添加了一些函数,这些函数可以在 JEXL 表达式中使用:
Map<String, Object> functions = new HashMap<String, Object>();
mFunctions = new ConstraintFunctions();
functions.put(null, mFunctions);
mEngine.setFunctions(functions);
但是,某些函数可能会引发异常,例如:
public String chosen(String questionId) throws NoAnswerException {
Question<?> question = mQuestionMap.get(questionId);
SingleSelectAnswer<?> answer = (SingleSelectAnswer<?>) question.getAnswer();
if (answer == null) {
throw new NoAnswerException(question);
}
return answer.getValue().getId();
}
当我解释表达式时,将调用自定义函数。表达式当然包含对此函数的调用:
String expression = "chosen('qID')";
Expression jexl = mEngine.createExpression(expression);
String questionId = (String) mExpression.evaluate(mJexlContext);
不幸的是,当这个函数在解释过程中被调用时,如果它抛出NoAnswerException
,解释器不会向我证明它,而是抛出一个一般的JEXLException
。有没有办法从自定义函数中捕获异常?为此,我使用了 apache commons JEXL 引擎,它在我的项目中用作库 jar。
经过一番调查,我找到了一个简单的解决方案!
当自定义函数中抛出异常时,JEXL 将抛出一个常规JEXLException
。但是,它巧妙地将原始异常包装在JEXLException
中,因为它是特别的原因。所以如果我们想抓住原文,我们可以写这样的东西:
try {
String questionId = (String) mExpression.evaluate(mJexlContext);
} catch (JexlException e) {
Exception original = e.getCause();
// do something with the original
}