DEV Community

Tom Holloway ๐Ÿ•
Tom Holloway ๐Ÿ•

Posted on • Edited on

Client-side global error handling and unhandled promise rejections

Open up the inspector in many websites you visit today and you are bound to see a few or more of these:

uncaught promise error

Uncaught errors can be a bit annoying if you don't know how to deal with them. Worse yet, if you don't have any visibility around them you may be relying on your users to report when these sort of errors happen. What would be better is to just funnel all these errors to your server.

onerror

The standard global error event handler to use is window.onerror. These sort of errors happen when (as per MDN states):

Error events are fired at various targets for different kinds of errors:

  • When a JavaScript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface ErrorEvent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addEventListener (not only capturing)).

  • When a resource (such as an img or script) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCapture set to True.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

Simply adding this to your code will help to make sure these common scenarios are properly captured.

window.onerror = function(message, source, lineno, colno, error) { ... };

onunhandledrejection

When dealing with Promise rejections, you will have to use a different approach. According to MDN you'll find the following window.onunhandledrejection. It states as such:

The onunhandledrejection property of the WindowEventHandlers mixin is the EventHandler for processing unhandledrejection events. These events are raised for unhandled Promise rejections.

You can easily capture unhandled promise rejections from anywhere in your codebase with the following script:

window.onunhandledrejection = function (e) {
    // e.reason is the value returned in the rejection
}

Conclusion

Global error handling can help make sure you always keep a keen eye on what's happening in your web application when you aren't looking. I will often pair these event handlers with some kind of mechanism to store the logs in localStorage (when networking is unavailable) or otherwise simply post them to a backend api to log what happened and in what context.

Bonus: try adding in some simple trace behaviors to help give you an idea of what the user was doing up until this point where that unhandled error occurs.

Best of luck!

Top comments (0)