15

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.

1
  • In Chrome, I confirm that window.onerror fails to catch an error in a script file, whether or not dev tools are running. Commented Aug 28, 2024 at 13:48

4 Answers 4

16

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);
Sign up to request clarification or add additional context in comments.

6 Comments

That's right. And WebKit has recently made some advance on fixing that bug. It's not fixed yet, but here you have the link for updates: bugs.webkit.org/show_bug.cgi?id=8519
According to groups.google.com/group/js-test-driver/browse_thread/thread/… it should be fixed in Chrome 10
I'm using Chrome 14 (the latest release) and window.onerror works!
I'm using Chrome Version 128.0.6613.84 (Official Build) (64-bit) and window.onerror fails to catch errors in script files. Makes it hard to handle JavaScript errors similarly to PHP errors.
@DavidSpector Without a reproduction of your code it's hard to assist you. It could be that there is an eventhandler firing before on the error events. Have you tried using the addEventListener syntax?
|
6
window.onerror = function(errorMsg, url, lineNumber) {
    // Code to run when an error has occurred on the page
}

2 Comments

An explanation would be in order.
Doesn't work for me. When I use an undefined variable inside a <script> file, the error message shows in browser > dev tools > console as an uncaught error. window.onerror = function at top of script is not called!
0

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 JavaScript feature (GitHub Issue 11999) ... to add support to this issue, log in to GitHub and "react" with a "Thumbs Up" on the original post (don't +1 in comments).

Current Google documentation for window.onerror

Information from InternetWayback page regarding window.onerror ::

Handle runtime exceptions using window.onerror Chrome exposes the window.onerror handler function, called whenever an error happens in the JavaScript code execution. Whenever a JavaScript exception is thrown in the window context and is not caught by a try/catch block, the function is invoked with the exception's message, the URL of the file where the exception was thrown, and the line number in that file, passed as three arguments in that order.

You may find it useful to set an error handler that would collect information about uncaught exceptions and report it back to your server using an AJAX POST call, for example. In this way, you can log all the errors happening in the user's browser, and be notified about them.

Example of using window.onerror:

Example of using window.onerror

The error event is fired on a Window object when a resource failed to load or couldn't be used — for example if a script has an execution error.

window.onerror = (a, b, c, d, e) => {
  console.log(`message: ${a}`);
  console.log(`source: ${b}`);
  console.log(`lineno: ${c}`);
  console.log(`colno: ${d}`);
  console.log(`error: ${e}`);

  return true;
};

Note: Due to historical reasons, onerror on window is the only event handler property that receives more than one argument.

2 Comments

Last link does not mention window.onerror at all.
@DavidSpector updated answer; the link "was" to the correct page (when originally answered.) A little internet wayback magic; and voila, answer from the past. Of course, where the link currently goes is useful for present day versions of Chrome; so we've both now.
-1

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

2 Comments

Latest releases of Safari (and Chrome) do support it. For reference, I confirmed on Safari 5.1 and Chrome 14, both in Mac OS X. Not sure when they were finally added to those browsers, but it's now available on all major browsers.
It may be available, but it doesn't appear to handle errors in script files in Chrome Version 128.0.6613.84 (Official Build) (64-bit).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.