eval javascript, check for syntax error

Jesus Ramos picture Jesus Ramos · Feb 7, 2011 · Viewed 46.3k times · Source

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?

Answer

ChaosPandion picture ChaosPandion · Feb 7, 2011

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

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