eval javascript, check for syntax error

一个人想着一个人 提交于 2019-11-27 01:08:21

问题


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?


回答1:


You can test to see if an error is indeed a SyntaxError.

try {
    eval(code); 
} catch (e) {
    if (e instanceof SyntaxError) {
        alert(e.message);
    }
}



回答2:


When using try catch for catching particular type of error one should ensure that other types of exceptions are not supressed. Otherwise if evaluated code would throw a different kind of exception it could disappear and cause unexpected behavior of code.

I would suggest writting code like this:

try {
    eval(code); 
} catch (e) {
    if (e instanceof SyntaxError) {
        alert(e.message);
    } else {
        throw( e );
    }
}

Please note the "else" section.




回答3:


You can use JsLint which contains a javascript parser written in javascript. It will give you lots of information about your code, it can be configured to be more relaxed or not, etc...




回答4:


According to the Mozilla documentation for eval:

eval returns the value of the last expression evaluated.

So I think you may be out of luck. This same document also recommends against using 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.

So regardless, please be aware of the risks before using this function.



来源:https://stackoverflow.com/questions/4923316/eval-javascript-check-for-syntax-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!