Catching unforeseen JavaScript errors

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.