Skip to content
Amal Hashim
All posts
Snippet

JavaScript - Global error handler

Catch every unhandled JavaScript error on a page with window.onerror and show the message, URL and line number.

1 min read#JavaScript

Set window.onerror to catch any error that is not handled elsewhere on the page. The browser passes the message, the script URL and the line number.

js
window.onerror = function(error, url, line) {
    var errorDetails = "Error Description = " + error;
    errorDetails += "\nUrl = " + url;
    errorDetails += "\nLine Number = " + line;

    alert(errorDetails);
};

In a real site, send the details to the server instead of showing an alert.