Is it possible to programatically catch JavaScript SyntaxErrors?

Posted by Matty on Stack Overflow See other posts from Stack Overflow or by Matty
Published on 2010-03-26T19:27:37Z Indexed on 2010/03/26 19:43 UTC
Read the original article Hit count: 393

Filed under:
|
|

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, or ASP. This program is intended to build another program written in JavaScript. However, the first program is unfortunately not immune to errors. So, occasionally, the program which builds the JavaScript program does some funky stuff and outputs a syntax error in the JavaScript source. Now some user goes and loads the program and it essentially halts, because the web browser running it can't properly parse the JavaScript. This user is probably not going to be happy. I wouldn't be.

This brings me to my question. Is it possible to write an error handler that would catch these kind of syntax problems allowing the application to fail gracefully?

Here's an example:

    <html>
  <head>
   <script type="text/javascript" charset="utf-8">
    window.onerror = errorHandler;
    function errorHandler(a,b,c) {
     alert('horray!  No wait, Booo!');
    }
    vara jfs;
   </script>
  </head>
  <body>
   Can this be done?
  </body>
 </html>

or

<html>
  <head>
   <script type="text/javascript" charset="utf-8">
    try {
     vara jfs;
    } catch  (e) {
     alert('horray!  No wait, Booo!');
    }
   </script>
  </head>
  <body>
   Can this be done?
  </body>
 </html>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about error-handling