Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 827
Jack Avatar asked Mar 05 '10 05:03

Jack


People also ask

How do you handle exceptions globally?

The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file. The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class.

How do I create a global error handler?

Steps for phase 2 implementation: Defining “Global Error Handler Configuration” Step 1: Select the “Global Elements” tab in Anypoint Studio. Step 1b: The “Global Configuration Elements” panel will appear. Step 2: Select the “Create” button from the “Global Configuration Elements” panel.

How many global exception handlers are there?

Only one Global Exception Handler can be set per automation project. By default, the template retries the exception 3 times before aborting the execution. This default behavior can be changed from inside the template.

How do you handle exceptions in JavaScript?

As with many programming languages, the primary method of dealing with exceptions in JavaScript is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution.


1 Answers

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.

like image 98
Morten Avatar answered Oct 01 '22 02:10

Morten