eval javascript, check for syntax error

后端 未结 6 506
失恋的感觉
失恋的感觉 2020-12-08 09:50

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

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 10:37

    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.

    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.

提交回复
热议问题