how to catch ALL javascript errors with window.onerror? (including dojo)

jaronimoe picture jaronimoe · Dec 9, 2011 · Viewed 32.4k times · Source

this question is a follow-up to javascript: how to display script errors in a popup alert? where it was explained how to catch regular javascript errors using:

<script type="text/javascript">
    window.onerror = function(msg, url, linenumber) {
        alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
        return true;
    }
</script>

I tried it and found out that dojo erros like this one:

TypeError: this.canvas is undefined         dojo.js (Row 446)

were not reported using this method, which leads me to my question:

How can I report all javascript errors using window.onerror (especially dojo errors)?

Answer

Milad Naseri picture Milad Naseri · Dec 29, 2011

It could be Dojo is using proper Error handling methods (i.e. try-catch blocks) which prevents the exception from bubbling up and reaching the window container, on which you have registered the error handler.

If so, there is no way for you to do this. No error is going past the catch block, so no error handler is being called.

As pointed out by the comments, you can also use browser-specific debugging APIs like the Venkman hook and do break-on-error -- a solution that usually only works for privileged code (thanks to @Sam Hanes).

You can also do On(require, 'error', function () {}); to add error handling on DOJO's asynchronous script loader -- another point mentioned in the comments by @buggedcom