JavaScript errors can originate from anywhere inside your code or the libraries you’re using. Because they are runtime exceptions you’re not alerted to them whilst you’re writing your code. So you might not be aware of all the possible errors that might occur. Failing to foresee a specific error occurring might not turn out to be dramatic. Most of the time, the error is simply logged to the console and the application continues to functions properly. Sometimes they may lead to your browser freezing. But in the most problematic of cases you’re program may continue to appear to function correctly but the outcome is faulty.
How to deal with an error largely depends on the specific type of error and the context in which it has manifested itself. So there’s no silver bullet to be found on how to deal with unforeseen errors. But at least making sure that any uncaught errors don’t go unnoticed seems essential.
Web browsers provide a default event handler for error events that go to the window: window.onerror. However, the normal behavior for the browsers is to prevent error dialogs from displaying by setting the event handler to null: window.onerror = null;.
If we override the onerror event handler, and combine it for instance with the logToServer() method from my previous blog post, it is possible to gain some more insight into which errors are occurring where and when in our application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/* * Handle any uncaught JavaScript errors. */ window.onerror = function(msg, url, line, col, error) { // Log the location where the error occurred. var errorString = url + " (" + line + "," + col + "): " + msg + ", " + error; JDEV.logging.logToServer(errorString); // If you want to, you can bug the user about something unexpected that has happened. // Probably not what you'll want in production code, though ;) var alertMessage = "An error has occurred: " + error; alert(alertMessage); console.log(alertMessage); // Returning true will suppress error alerts (for older IE versions). var suppressErrorAlert = true; return suppressErrorAlert; }; |