Getting file names on stack traces.

A. Sundararajan sundararajan.athijegannathan at
Fri May 2 06:49:55 UTC 2014


Sorry for the delayed response (was on vacation). "eval naming" (//@ 
sourceURL or //# sourceURL) support has been added in jdk9 and 
backported to jdk8u-dev repo (most likely will be in 8u20).

import javax.script.*;

public class Main {
   public static void main(String[] args) throws Exception {
       ScriptEngineManager m = new ScriptEngineManager();
       ScriptEngine e = m.getEngineByName("nashorn");
       Compilable c = (Compilable)e;
       CompiledScript cs = c.compile("throw new Error();\n//# 

When you run the above code, you'll see myfile.js as source file name 
for that script frame throwing error.

Not just CompiledScript.eval - any eval - including engine.eval and 
script 'eval' function accept this // #sourceURL comment and use that 
value as name for the script "file". See also:


On Tuesday 22 April 2014 01:17 PM, Benjamin Sieffert wrote:
> Hi Greg,
> I've also tried to do this, but (without looking into it very extensively)
> didn't find a way other than to build a second string that wraps the first
> one like this:
> String scriptWithFileName = "load("
>      // will be shown as scriptname in stacktraces
>      + "{ name: \"" + name + '"' + ','
>      // the actual script
>      + "script:" + escapeJavaScript(script) + '"'
>      + '}'
>      + ')';
> It's working as intended and doesn't seem to have any unwanted
> side-effects, but of course it would be nice to be able to do this more
> cleanly from Java. I guess there's the possibility of calling the
> load-extension somewhere, but it doesn't seem to be public (Java) API.
> Hope this helps
> 2014-04-21 22:02 GMT+02:00 Greg Brail <greg at>:
>> Let's say that I have some JS code like this:
>> (function(foo) {
>>    throw new Error('Sorry, ' + foo);
>> })
>> and I execute it by reading it into a String variable, then executing it
>> using ScriptEngine.eval(string), and then I call the function later, either
>> from Java directly or from some other JS code.
>> Right now, in Nashorn, I see that the stack trace of my exception will
>> include the entry:
>> "<eval>:2"
>> to indicate the "file name" and line number of my error.
>> I would like instead to stick in a file name so that the file name appears
>> instead of "<eval>". Is there a way for me to do that?
>> I did try setting the property "ScriptEngine.FILENAME" on my script
>> context, but that seems to be a global context. It works the first time I
>> run the script, but if I call the function later on from inside another
>> script, the file name doesn't "stick" to the code.
>> I can provide an example if I need to, but is there anything you guys can
>> think of that I can do in order to get a file name to stick to this
>> function for the purpose of stack traces?
>> --
>> *greg brail* | *apigee <>* | twitter
>> @gbrail<>

More information about the nashorn-dev mailing list