Handling Errors in Event Handlers
Explain how to deal with exceptions thrown in event handlers that are not naturally caught by Error Boundaries.
window.addEventListener('error', function(event) {
// Log the error to the console
console.error('Captured error:', event.error);
// Prevent the default behaviour of the event
event.preventDefault();
});
This code snippet adds a global error handler that listens for any uncaught error that bubbles up to the window object. When an error occurs, it logs the error to the console and prevents the default browser handling, which might include logging to the console and reporting to the browser's error reporting service.
function safeEventHandler(handler) {
return function(event) {
try {
handler(event);
} catch (error) {
// Handle the error gracefully
console.error('Error occurred in event handler:', error);
// Possibly report the error to a remote error logging service
}
};
}
document.getElementById('myElement').addEventListener('click', safeEventHandler(function(event) {
// Your event handling logic here
// If an exception is thrown, it will be caught and logged
}));
Here we define a higher-order function `safeEventHandler` that takes an event handler function as input and returns a new function. This new function wraps the original event handler in a try-catch block to catch any thrown errors. By using this wrapper, we ensure that any exceptions thrown in the event handler are caught and handled gracefully. We can then attach the safe event handler to any DOM element.