You are here: Reference > JavaScript > client-side > event handling > events > onerror (window)

onerror event | error event (window)

Browser support:
Fires when a script error occurs.
You can use the try...catch statement to catch an error in JavaScript. If a script error occurs and the statement that has generated it is not inside a try...catch block, an onerror event is fired on the window.
Event handlers for the onerror event receive three parameters:
message String that specifies the error message.
URL String that specifies the location of the file where the error occurred.
line String that specifies the line number where the error occurred.
If an event handler for the onerror event returns true, then the script error does not generate an error message in the browser.

How to register:

In HTML:
This event cannot be registered in HTML.

In JavaScript:
object.onerror = handler;
object.addEventListener ("error", handler, useCapture);
9
object.attachEvent ("onerror", handler);
You can find the related objects in the Supported by objects section below.
The event object is accessible to all event handlers in all browsers. The properties of the event object contain additional information about the current event. To get further details about these properties and the possible event handler registration methods, please see the page for the event object.
For a complete list of events, see the page for Events in JavaScript.

Basic information:

Bubbles No
Cancelable Yes
Event object -

Actions that invoke the onerror event:

  • When a script error occurs.

Example HTML code 1:

This example illustrates the use of the onerror event:
<head>
    <script type="text/javascript">
        window.onerror = ErrorLog;
        function ErrorLog (msg, url, line) {
            alert ("error: " + msg + "\n" + "file: " + url + "\n" + "line: " + line);
            return true;    // avoid to display an error message in the browser
        }
        function ThrowError () {
            window.NotExistingFunction ();
        }
    </script>
</head>
<body>
    <button onclick="ThrowError ()">Throw an error</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example is similar to the previous one, but it uses the try...catch statement for error handling:
<head>
    <script type="text/javascript">
        function ThrowError () {
            try {
                window.NotExistingFunction ();
            }
            catch (e) {
                alert ("error: " + e.message);
            }
        }
    </script>
</head>
<body>
    <button onclick="ThrowError ()">Throw an error</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

External links:

User Contributed Comments

Post Content

Post Content