Is it possible to programatically catch JavaScript SyntaxErrors?

前端 未结 3 1058
囚心锁ツ
囚心锁ツ 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:45

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

     function load(file){
        var client = new XMLHttpRequest();
        client.open("GET", file, false);
        client.send(null);
        return client.responseText;
      }
    
      function include(file){
        try {
          eval(load(file));
        } catch (e) {
           alert("problem with file " + file);
        }
      }
    

提交回复
热议问题