Line No. in Rhino
Rhino is a great tool for developing javascript code, since it comes with a shell that let’s you run scripts from the command line and provides a REPL loop for quick try-outs. The command line is kind of long and unfriendly, but this can be taken care of with an alias or shell script:
java -classpath js.jar
org.mozilla.javascript.tools.shell.Main -f test.js
However, if you run a script that bombs out with an exception, you don’t get any line information, just the plain exception message:
js: uncaught JavaScript runtime exception:
TypeError: Cannot call method "charCodeAt" of undefined
To get line information, you need to ensure that rhino runs in interpretive mode, using the -opt -1 option:
java -classpath js.jar
org.mozilla.javascript.tools.shell.Main -opt -1 -f test.js
This results in:
js: "test.js", line 577: uncaught JavaScript runtime exception:
TypeError: Cannot call method "charCodeAt" of undefined
which has the offending line number, and thus is much more helpful. In addition, it it possible to get a stacktrace by invoking your code in a try catch block, and handling the exception as follows:
try {
// call your code here ...
}
catch (exc) {
print(exc);
if (exc.rhinoException)
exc.rhinoException.printStackTrace();
}
Don’t forget to specify the -opt -1 flag, since otherwise you’ll only see java-level calls. Also, note that the “rhinoException” property is defined on Error objects only, so the object caught should be explicitly tested for it.