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 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.
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.
来源:https://stackoverflow.com/questions/4923316/eval-javascript-check-for-syntax-error