1

我正在运行我自己的扩展 org.mozilla.javascript.ScriptableObject 的代理对象。我也有自己的扩展 org.mozilla.javascript.Function 的函数。

我的愿望是让这里抛出的任何异常返回行号,如果可能的话,返回它们在评估脚本中出现的列号。这可能吗?我只能访问上下文和范围。

4

1 回答 1

1

每当脚本抛出异常时,Rhino 都会抛出 RhinoException,它已经有行号和列号(以及更多)。但是,当您执行脚本时,您需要提供 Rhino 将使用的行号作为起始行号。发生异常/错误的实际行号将与此数字相关。所以有些东西是这样的:

//-- Define a simple test script to test if things are working or not.
String testScript = "function simpleJavascriptFunction() {" +
                    "  this line has syntax error." +
                    "}" +
                    "simpleJavascriptFunction();";
//-- Compile the test script.
Script compiledScript = Context.getCurrentContext().compileString(testScript, "My Test Script", 2, null);
//-- Execute the test script.
compiledScript.exec(Context.getCurrentContext(), anyJavascriptScope);

在上面的代码中,起始行号设置为 2(调用 compileString() 的第三个参数)。执行此操作时,Rhino 将抛出一个 RhinoException,它将 lineNumber 属性设置为值 '3'(第一行被视为我们传递 2 的第二行 b/c)。

希望这可以帮助。

于 2013-05-15T12:12:01.933 回答