Pete Verdon wrote:
I'm working on a fairly sizeable javascript application. I recently
added some error-handling to it, using window.onerror to catch them.
This sometimes works and sometimes doesn't; if I introduce a deliberate
mistake "near the top" of the system then it's trapped and handled
properly, but there's lots of code where mistakes only show up in my
Firebug console.
My first thought is that, since a lot of the work happens in callbacks
after an XMLHTTPRequest, this somehow puts the error handler out of
scope. However, logging "window" to my Firebug console, in such a
callback, just before deliberately invalid code, shows that it has a
suitable onerror function but that it is not called. Does anyone know
why this might be?
Most probably because you have a wrong idea of what does onerror
handler do.
window.onerror is a very primitive way to do something (say inform
user) *after* the execution broke because of an error. It was widely
used at old times (before try-catch) only because of the lack of
anything better.
Let me stress it once again: the execution breaks first, window.onerror
is called only after. You can return true from the handler, but it has
nothing to do with VB-like OnError Resume Next or similar.
It simply prevents the error notification to appear in the browser
statusbar (where such behavior exists). This way
window.onerror = function(){return true;};
// prevent visual error notification
is the only task window.onerror can be really used.
If you want an exception handling in your program (with possible
execution continued after the exception handled) then try-catch blocks
are the only way.