eval() Exception - line number

1,181 views
Skip to first unread message

Ohad

unread,
Aug 15, 2010, 4:24:49 PM8/15/10
to nodejs
I have a var str = ".a long string that contains many lines..." In
case of exception that caused by eval(str);

I had like to catch it and print the the line number that caused the
exception. (the line internal to str..)

Is it possible?

Ohad

unread,
Aug 15, 2010, 5:08:55 PM8/15/10
to nodejs
I found a solution which is pretty inefficient, yet I only use it when
debug_mode==1 so it's not that bad..

I write the eval_str to a file, I "import that file, and invoke it
inside a try{}catch{} and I parse the error line from the stack
trace...

In my specific case, this is how the code looks like:

var errFileContent = "exports.run = "+evalStringAsAFunction+";";
fs.writeFile('/home/vadmin/Alligator/lib/debugging.js',
errFileContent, function (err) {
var debug = require('./debugging');
try{
debug.run(args...);
}
catch(er){
log.debug(parseg(er));
}
});

weepy

unread,
Aug 15, 2010, 5:31:12 PM8/15/10
to nodejs
thanks .. i wanted to do something very similar. I'll try your
approach

mscdex

unread,
Aug 15, 2010, 5:37:51 PM8/15/10
to nodejs
You can get a stack trace that includes the line number inside the
string, but not with eval. For that you have to use the Script module.
Something like this:

var Script=process.binding('evals').Script;
var js = "var a=0;\nvarb=1;\nthrow new Error('lol');";

try {
Script.runInThisContext(js, 'eval');
console.log('no exception');
} catch (err) {
console.log(err.stack);
}


will give you:

Error: lol
at eval:3:7
at Object.<anonymous> (/home/mscdex/tmp/eval.js:5:10)
at Module._compile (node.js:472:25)
at Module._loadScriptSync (node.js:482:10)
at Module.loadSync (node.js:352:12)
at Object.runMain (node.js:535:24)
at node.js:760:10

If you want to parse out the line number, you could do:

var lineNumber = /\s+at eval:(\d+):.+\n/mi.exec(err.stack)[1];
console.log(lineNumber); // 3

Ohad

unread,
Aug 16, 2010, 2:02:57 AM8/16/10
to nodejs
It seems like it does the same thing as I have suggested, it creates a
temp file - tmp/eval.js and runs it,
nice! thanks.

weepy

unread,
Aug 16, 2010, 3:10:53 AM8/16/10
to nodejs
Is there any way to pick up on syntax errors ?

It seems that there is an exception that's thrown with a message, but
it's not possible to get the linenumber that it occured at ?

mscdex

unread,
Aug 16, 2010, 5:22:45 AM8/16/10
to nodejs
On Aug 16, 2:02 am, Ohad <mro...@gmail.com> wrote:
> It seems like it does the same thing as I have suggested, it creates a
> temp file - tmp/eval.js and runs it,
> nice! thanks.

No, it doesn't create a file at all. "tmp/eval.js" is the just the
file containing the code I listed :-)
Reply all
Reply to author
Forward
0 new messages