Global javascript exception handler (in Chrome)

2020-06-12 02:17发布

问题:

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

EDIT: window.onerror didnt work, 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. Developer console registers the uncaught exception, but the alert() in window.onerror does not appear.

回答1:

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

What I did was to wrap 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, apparently it wasn't implemented in WebKit.



回答2:

window.onerror = function(errorMsg, url, lineNumber) {
    // code to run when error has occured on page
}


回答3:

Chrome Support for window.onerror

  • I believe support started in Chrome v10 (Chromium Issue 7771), but it looks as if "full" support with CORS support was resolved around Chrome 30+ (Chromium Issue 159566)
  • caniuse.com doesn't currently track this JS feature (GitHub Issue 11999) ... to add support to this issue, login to GitHub & "react" with a "Thumbs Up" on the original post (don't +1 in comments.)

Current Google Documentation for window.onerror

  • Chrome DevTools ~ Handle runtime exceptions using window.onerror


回答4:

Perhaps you're looking for window.onerror Not sure whether this is available on all browsers.