Search code examples
javascriptexceptionevalnode.jsv8

Javascript eval() Exception - line number


In JavaScript 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?

EDIT As part of the Alligator project (http://github.com/mrohad/Alligator), an application server for JavaScript, I am reading files from the disk and eval() anything that is nested to a scriplet( < ? ? > )

I am running this script outside a browser, using NodeJS (on top of V8).


Solution

  • 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));
        }
    });