Is it possible to programatically catch JavaScript SyntaxErrors?

前端 未结 3 1057
囚心锁ツ
囚心锁ツ 2021-01-16 04:11

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

3条回答
  •  心在旅途
    2021-01-16 04:40

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

    function say(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}"
    ];
    
    function verifyScriptlet(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);
    

提交回复
热议问题