Javascript eval() 异常 - 行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3488994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript eval() Exception - line number
提问by DuduAlul
In JavaScript I have a var str = ".a long string that contains many lines..."In case of exception that caused by eval(str);
在 JavaScript 中,我有一个var str = ".a long string that contains many lines..."In case 引起的异常eval(str);
I had like to catch it and print the the line number that caused the exception. (the line internal to str..)
我想捕获它并打印导致异常的行号。( str 内部的行..)
Is it possible?
是否可以?
EDITAs 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( < ? ? > )
编辑作为 Alligator 项目 ( http://github.com/mrohad/Alligator) 的一部分,JavaScript 的应用程序服务器,我正在从磁盘和 eval() 读取任何嵌套到脚本中的文件( < ? ? > )
I am running this script outside a browser, using NodeJS (on top of V8).
我在浏览器外运行这个脚本,使用 NodeJS(在 V8 之上)。
采纳答案by DuduAlul
I found a solution which is pretty inefficient, yet I only use it when debug_mode==1 so it's not that bad..
我找到了一个效率很低的解决方案,但我只在 debug_mode==1 时使用它,所以它并没有那么糟糕..
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...
我将 eval_str 写入文件,然后“导入该文件,并在 try{}catch{} 中调用它,然后从堆栈跟踪中解析错误行...
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));
}
});
回答by Steve Brewer
Try adding the try/catch to the string instead of around the eval:
尝试将 try/catch 添加到字符串而不是在 eval 周围:
var code = 'try{\nvar c = thisFuncIsNotDefined();\n}catch(e){alert(e.lineNumber);}';
回答by AndreyKo
1) Run:
1)运行:
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
}
回答by Topera
This solves your problem?
这解决了你的问题?
try {
eval(str);
} catch (e) {
console.log(e.lineNumber)
}

