How to handle errors globally With the onerror() Method in Javascript

The onerror() method is available to all HTML elements for handling any errors that may occur with them. For instance, if an img tag cannot find the image whose URL is specified, it fires its onerror method to allow the user to handle the error.

Typically, you would provide another image URL in the onerror call for the img tag to fall back to. This is how you can do that via JavaScript:

const image = document.querySelector("img")

image.onerror = (event) => {
    console.log("Error occurred: " + event)
}

However, you can use this feature to create a global error handling mechanism for your app. Here’s how you can do it:

window.onerror = (event) => {
    console.log("Error occurred: " + event)
}

With this event handler, you can get rid of the multiple try...catch blocks lying around in your code and centralize your app’s error handling similar to event handling.

Leave a comment

Your email address will not be published. Required fields are marked *