开发者

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 li开发者_高级运维ke 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).


Try adding the try/catch to the string instead of around the eval:

var code = 'try{\nvar c = thisFuncIsNotDefined();\n}catch(e){alert(e.lineNumber);}';


1) Run:

var javascript_offset;
try {
  undefined_function();
} catch(ex1) {
  javascript_offset = ex1.lineNumber;
}
try {
  YOUR_STRING_WITH_JS
} catch (ex2) {
  var line_that_caused_it = ex2.lineNumber - javascript_offset -2;
  HANDLE_THE_EXCEPTION_HERE
}


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


This solves your problem?

try {
    eval(str);
} catch (e) {
    console.log(e.lineNumber)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜