eval javascript, check for syntax error

两盒软妹~` 提交于 2019-11-28 05:43:36

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

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

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.

Pablo Grisafi

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...

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.

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