How to set correct fileName for exceptions thrown from a function in a Function object
Tim Fox
timvolpe at gmail.com
Wed Feb 18 09:40:13 UTC 2015
Hi all,
I'm currently using a CommonJS/npm modules require implementation
(npm-jvm) with Nashorn.
Roughly, the way it works (and I'm sure you're already familiar with
this technique) is it takes the JavaScript module and wraps it in a
Function object:
var body = readScriptAsText();
var args = ['exports', 'module', 'require', '__filename', '__dirname'];
var func = new Function(args, body);
func.apply(module, [module.exports, module, module.require,
module.filename, dir]); // Execute it - this works fine
Now let's say the actual module (foomodule.js) we are loading contains this:
module.exports = function() {
var num = 234;
num.substr(1, 1); // Will throw TypeError here
}
I.e. it simply exports a function, which will throw a TypeError when
it's executed.
When the exported function is executed it does indeed throw a TypeError:
var f = require("foomodule");
f(); // Throws TypeError
Unfortunately the fileName field of the TypeError is set to "<function>"
not to "foomodule.js", which is unfriendly for the user.
This is understandable as the Function object which wraps the module
doesn't know about "foomodule.js".
So.. my question is.. how do I tell the Function object that the
"filename" it should use when exceptions are thrown from it is
"foomodule.js"?
I have tried the following and none work:
var func = new Function(args, body);
func.name = "foomodule.js";
func.fileName = "foomodule.js";
func.displayName = "foomodule.js";
Any insights would be greatly appreciated.
More information about the nashorn-dev
mailing list