Skip to content Skip to sidebar Skip to footer

Is It Possible To Programatically Catch Javascript Syntaxerrors?

I don't think that this is doable, but wanted to throw it out to the community to confirm my suspicions. Let's say you're writing a program in another language like Python, PHP,

Solution 1:

Generally, a programming language is parsed, and if that succeeds possibly compiled to another form, and if that succeeds then interpreted/executed on hardware or a vm. Just because code passes one phase, doesn't mean it's valid code.

You are asking if code running in the last phase, can be aware of problems encountered in the first part and deal with it.

Some languages offer various hooks into it's own parsing and compiling mechanism. As Cheeso mentioned, eval is Javascript's way of calling into this mechanism.

Rather than wrapping all of your scripts in strings, it might be nicer to leave them in javascript files, and load them into your main program with the following javascript (or similar).

functionload(file){
    var client = newXMLHttpRequest();
    client.open("GET", file, false);
    client.send(null);
    return client.responseText;
  }

  functioninclude(file){
    try {
      eval(load(file));
    } catch (e) {
       alert("problem with file " + file);
    }
  }

Solution 2:

Google has released their Closure toolset which includes a JavaScript compiler and minimizer. I haven't used it personally but have heard a lot of great things. Also, it apparently helps you locate browser compatibility issues.

I don't think it will help you to perform real-time analysis, but still could be a valuable tool.

Solution 3:

If you are comfortable with the security exposure, you could call eval() on the code in question to detect syntax errors.

functionsay(x) { ... emit message in some way.... }

var scriptlets = [
    "foof1 = function(a) {if (a == 7) { return \"A-OK\"; } } ",
    "foof2 = function (a) {if argle bargle seventy 7, then this isn't going to work}"
];

functionverifyScriptlet(n) {
    var s = scriptlets[n];
    try {
        var x = eval(s);
        say("verified #"+ n +", result: " + (typeof x));
    }
    catch (exc1)
    {
        say("Exception while verifying #"+ n +": " + exc1.message);
    }
}

verifyScriptlet(0);
verifyScriptlet(1);

Post a Comment for "Is It Possible To Programatically Catch Javascript Syntaxerrors?"