eval javascript,检查语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4923316/
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
eval javascript, check for syntax error
提问by Jesus Ramos
I wanted to know if it is possible to find through javascript if a call to eval() has a syntax error or undefined variable, etc... so lets say I use eval for some arbitrary javascript is there a way to capture the error output of that eval?
我想知道是否可以通过 javascript 找到对 eval() 的调用是否有语法错误或未定义的变量等......所以可以说我对某些任意 javascript 使用 eval 有没有办法捕获错误输出那个评估?
回答by ChaosPandion
You can test to see if an error is indeed a SyntaxError.
您可以测试以查看错误是否确实是 SyntaxError。
try {
eval(code);
} catch (e) {
if (e instanceof SyntaxError) {
alert(e.message);
}
}
回答by RandomX
When using try-catch for catching a particular type of error one should ensure that other types of exceptions are not suppressed. Otherwise if the evaluated code throws a different kind of exception it could disappear and cause unexpected behaviour of the code.
当使用 try-catch 捕获特定类型的错误时,应确保不会抑制其他类型的异常。否则,如果评估的代码抛出不同类型的异常,它可能会消失并导致代码的意外行为。
I would suggest writing code like this:
我建议写这样的代码:
try {
eval(code);
} catch (e) {
if (e instanceof SyntaxError) {
alert(e.message);
} else {
throw e;
}
}
Please note the "else" section.
请注意“其他”部分。
回答by Pablo Grisafi
回答by Justin Ethier
According to the Mozilla documentation for eval
:
eval returns the value of the last expression evaluated.
eval 返回评估的最后一个表达式的值。
So I think you may be out of luck. This same document also recommends against using eval
:
所以我认为你可能不走运。同一文档还建议不要使用eval
:
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.
eval() 是一个危险的函数,它以调用者的权限执行它传递的代码。如果您使用可能受到恶意方影响的字符串运行 eval(),您最终可能会在具有您的网页/扩展程序权限的用户计算机上运行恶意代码。更重要的是,第三方代码可以看到调用 eval() 的范围,这可能会导致类似 Function 不易受到攻击的可能攻击方式。
So regardless, please be aware of the risks before using this function.
所以无论如何,请在使用此功能之前了解风险。
回答by Sean
To continue using the code after validation, I use the following example:
要在验证后继续使用代码,我使用以下示例:
var validCode = 1;
try {
eval( jsCode ); /* Code test */
} catch (e) {
if (e instanceof SyntaxError) {
validCode = 0;
console.warn(e.message);
}
} finally {
if(validCode){
"do some magic"
}
}