Jesus Ramos
Jesus Ramos

Reputation: 23268

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?

Upvotes: 49

Views: 64021

Answers (7)

sub0d33p
sub0d33p

Reputation: 1

put your desired value for b

    //b="4+6";
    try { eval(b); } 
    catch (err) {
       if (err instanceof SyntaxError)
          document.getElementById('screen').innerHTML = "<i>Syntax Error</i>";

        /*In html make a div and put id "screen" in it for this to work
        you can also replace this line with document.write or alert as per your wish*/
    }
    finally {
         document.getElementById('screen').innerHTML = eval(b); //outputs answer
    }

Upvotes: 0

Balaji
Balaji

Reputation: 10887

This Below code posted by go-oleg thanks to him

This code validate the correct syntax otherwise return error

Note:code is not vaildate run time error because it uses ast parser to analyze the correct syntax.

To Install

npm install esprima --save

code:

var esprima = require('esprima');
var userStringToTest = 'var a = 50;';

var isValid = isValidJs(userStringToTest);

if(isValid) {
  alert('its validated!');
}
else {
  console.log('its NOT valid syntax!');
}

function isValidJs(testString) {
  var isValid = true;
  try {
    esprima.parse(testString);
  }
  catch(e) {
    isValid = false;
  }
  return isValid;
}

Upvotes: 1

Sean
Sean

Reputation: 37

To continue using the code after validation, I use the following example:

var validCode = 1;
try {
  eval( jsCode );        /* Code test */
} catch (e) {
  if (e instanceof SyntaxError) {
    validCode = 0;
    console.warn(e.message);
  }
} finally {
  if(validCode){
    "do some magic"
  }
}

Upvotes: 1

RandomX
RandomX

Reputation: 199

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.

Upvotes: 15

Pablo Grisafi
Pablo Grisafi

Reputation: 5047

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

Upvotes: 3

Justin Ethier
Justin Ethier

Reputation: 134167

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.

Upvotes: 4

ChaosPandion
ChaosPandion

Reputation: 78262

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

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

Upvotes: 82

Related Questions