我有一个使用 Activiti 引擎的项目。 它支持使用 Nashorn 运行脚本。 我在脚本任务或任务监听器中运行此代码都没有问题。 但是在使用执行监听器时我遇到了问题。
在我的脚本中,我想抛出一个应该被 java 代码捕获的错误。 例如:
throw new Error("this is an error");
但是我得到一个错误:
problem evaluating script: Error: this is an error in scripts/error.js at line number 8 at column number 1
我最初也试过这个:
var BpmnError = Java.type(org.activiti.engine.delegate.BpmnError');
throw new BpmnError("BusinessExeptionOccured","a Message");
在这种情况下,没有错误被捕获,就好像抛出从未发生过一样。
在 Activiti 文档中它指出:
As of Activiti 5.9, it is possible to throw BPMN Errors from user code inside Service Tasks or Script Tasks. In order to do this, a special ActivitiException called BpmnError can be thrown in JavaDelegates or scripts
我还没有找到任何例子来说明如何做到这一点。
我也没有看到任何可以抛出 jdk.nashorn.internal.runtime.ECMAException 的 JavaScript 代码示例 opendJDK ECMAException 中的评论指出:
Exception used to implement ECMAScript "throw" from scripts.
如有任何帮助,我们将不胜感激。
最佳答案
您可以捕获 ScriptException,然后从那里访问抛出的 ECMAScript 对象。
示例代码:
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
try {
e.eval("throw new Error('this is an error');");
} catch (ScriptException se) {
// get the original cause
Throwable cause = se.getCause();
// in this case, the cause is a nashorn exception
if (cause instanceof NashornException) {
NashornException ne = (NashornException)cause;
// Access the underlying ECMAScript error object thrown
Object obj = ne.getEcmaError();
// print ECMA object 'as is'
System.out.println(obj);
// In this example, the thrown ECMAScript object is
// an instanceof Error. Script objects are accessible
// as JSObject in java code.
if (obj instanceof JSObject) {
JSObject jsObj = (JSObject)obj;
System.out.println(jsObj.getMember("message"));
System.out.println(jsObj.getMember("name"));
// access nashorn specific 'stack' property
System.out.println("stack trace: " + jsObj.getMember("stack"));
}
}
}
}
}
关于javascript - 从 javascript 内部抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35634547/