捕获JEXL中自定义函数引发的异常 [英] Catch exception thrown by custom function in JEXL
问题描述
我在JEXL引擎中添加了一些功能,这些功能可以在JEXL表达式中使用:
I added some functions to the JEXL engine wich can be used in the JEXL expressions:
Map<String, Object> functions = new HashMap<String, Object>();
mFunctions = new ConstraintFunctions();
functions.put(null, mFunctions);
mEngine.setFunctions(functions);
但是,某些函数会引发异常,例如:
However, some functions can throw exceptions, for example:
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();
}
当我解释一个表达式时,将调用自定义函数.该表达式当然包含对此函数的调用:
The custom function is called when i interpret an expression. The expression of course holds a call to this function:
String expression = "chosen('qID')";
Expression jexl = mEngine.createExpression(expression);
String questionId = (String) mExpression.evaluate(mJexlContext);
不幸的是,在解释过程中调用此函数时,如果它抛出NoAnswerException
,则解释器不会向我派遣它,而是抛出通用的JEXLException
.有什么方法可以从自定义函数中捕获异常?我为此使用了 apache commons JEXL 引擎,我的项目中的库jar.
Unfortunetaly, when this function is called in course of interpretation, if it throws the NoAnswerException
, the interpreter does not propagete it to me, but throws a general JEXLException
. Is there any way to catch exceptions from custom functions? I use the apache commons JEXL engine for this, which is used as a library jar in my project.
推荐答案
经过一番调查,我发现了一个简单的解决方案!
After some investigation, i found an easy solution!
在自定义函数中引发异常时,JEXL将引发常规JEXLException
.但是,它巧妙地将原始异常包装在JEXLException
中,特别是由于原因.因此,如果要捕捉原始图像,可以编写如下内容:
When an exception is thrown in a custom function, JEXL will throw a general JEXLException
. However, it smartly wraps the original exception in the JEXLException
, as it's cause in particular. So if we want to catch the original, we can write something like this:
try {
String questionId = (String) mExpression.evaluate(mJexlContext);
} catch (JexlException e) {
Exception original = e.getCause();
// do something with the original
}
这篇关于捕获JEXL中自定义函数引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!