views:

148

answers:

1

[Update. I need to be more precise, I see...] See the following example in javascript:

<html>
  <head>
    <script>
      window.onerror = function() {
        alert('error'); // this one works
        try {i.dont.exist += 0;}
        catch(e) {
          // do some stacktrace stuff, this does not trigger
          alert(e.stack);
        }
      };
    </script>
    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js' type='text/javascript'></script>
    <script>
      $(document).ready(function() {
        foo[1]++;
      });
    </script>
  </head>
<body>
  <p>Hello world.</p>
</body>
</html>

The 2. alert is not triggered. Why? If I replace "foo[1]++" by "this is a bogus line" everything works and both alerts are triggered. Is there some run-time error problem?

+1  A: 

The alert is not triggered because your error handler function was not successfully defined, due to your Javascript error :-) That block of code can't be parsed correctly so it isn't run.

Set it up this way:

<script>
  $(function() {
    window.onerror = function() {
      // ...
    };
  });
</script>

If it's in its own script tag, then it'll be OK. Now, you may want to reconsider delaying the definition of your error handler to the "ready" event handling, since you may have errors before that point is reached.

[edit] OK here is a complete example, and it works fine for me:

 <html>
   <head>
     <script>
       window.onerror = function() {
         alert("OH NO THERE HAS BEEN AN ERROR!");
       };
     </script>
     <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js' type='text/javascript'></script>
     <script>
       $(function() {
          here is some bogus stuff that will cause Javascript parse errors.
       });
     </script>
   </head>
   <body>
     <p>Hello world.</p>
   </body>
 </html>
Pointy
ok, I moved the onerror Handler to its own script tag. It doesn't change the behavior, that an error inside the ready-function does not trigger the "stack"...
2ni
check my update to the answer
Pointy
thx for your complete example. This works for me too, but it's not the point. I updated my not working example above.
2ni
Well, 2 things. First, the "onerror" function is not called when an exception is caught. Second, as far as I can tell, window.onerror just isn't called when there's an error/exception thrown in it. In fact I can't even get try/catch to work properly. Based on some comments here [https://bugzilla.mozilla.org/show_bug.cgi?id=65683#c20] it looks to me as if "window.onerror" is effectively deprecated; it seems to predate the "try/catch" mechanism.
Pointy