Search code examples
javascriptgoogle-chromeexception

Global JavaScript exception handler (in Chrome)


How do I overwrite the global Exception handler in JavaScript so that it becomes the top level handler for all uncaught exceptions?

window.onerror didn’t work. The code is:

<HTML>
    <HEAD>
        <script language='javascript'>
            window.onerror = function (em, url, ln) {
                alert(em + ", " + url + ", " + ln);
                return false;
            }

            function fGo() {
                try
                {
                    var a = b; // Error here: b not defined
                }
                catch (e)
                {
                    throw e;
                }
            }
        </script>
    </HEAD>

    <BODY>
        <button onclick='fGo()'>GO</button>
    </BODY>
</HTML>

I'm testing on Chrome, by the way. The developer console registers the uncaught exception, but the alert() in window.onerror does not appear.


Solution

  • As of 2013, Chrome supports the window.onerror. (I have version 25, and comments imply earlier versions as well.)

    I wrapped jQuery using currying to create a proxy that always does a try...catch in the jQuery functions.

    I use it in www.js-analytics.com. However, the solution only holds for jQuery scripts.

    Before 2013 Google Chrome didn't support window.onerror, and apparently it wasn't implemented in WebKit.

    Running the following in the Chrome dev console on will cause it to trigger the onerror handler and log test to the console.

    window.onerror = ()=>console.log('test');
    function assert(){x+3}
    setTimeout(assert, 0);