eval javascript, check for syntax error

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?


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