Search code examples
javascriptjavanashornscriptengine

How do you get the JavaScript stack trace from Nashorn?


I have a script that works just fine in Chrome but crashes on Nashorn with:

(Error: Namespace "com.cognitect.transit.util" already declared. in at line number 19664 at column number 6

That error is not very useful, as that line contains:

  throw Error('Namespace "' + name + '" already declared.');

I need to get a full stack trace from Nashorn, I found NashornException.getScriptStackString but the error Nashorn is generating is of type javax.script.ScriptException which gives me an empty string when I call NashornException.getScriptStackString.

How do I get an JavaScript stack trace from Nashorn?

I don't want to do it from JavaScript, I want to do it the same way the browser does it, no matter what JS code you are running. A lot of my JS code is third party, it's generated, I cannot modify the thousand of functions I have to print exceptions just in case.


Solution

  • The NashornException is available as cause of the ScriptException:

    import jdk.nashorn.api.scripting.NashornException;
    
    ...
    
    catch (ScriptException e) {
         if (e.getCause() instance of NashornException) 
             String jsStackTrace = NashornException.getScriptStackString(e.getCause());
    }