Handling Uncatched Promise Rejections in Browser

javascript
Published on December 19, 2018

The Background

While implementing Promises, you need to handle rejections and catch them accordingly. If the Promise rejection is not handled, an error will be thrown in the browser's console.

// rejection is not handled
Promise.reject('An error occurred');

Rejected promises should be handled with catch method or within a try-catch block.

// rejection is handled here
Promise.reject('An error occurred').catch(function() {
	console.log('Catched');
});

However sometimes Promise rejections may not be implemented, for some reason. This is definitely a wrong practice, but it may happen.

Taking such a scenario in consideration, modern browsers have brought forward unhandledrejection event that can handle such a situation.

The unhandledrejection Event

unhandledrejection event is fired when a Promise is rejected, but there is no rejection handler function implemented in the code.

Furthermore, with preventDefault you can prevent the default action. With this the error will not be thrown to the browser console.

window.addEventListener('unhandledrejection', function(e) {
	console.log('Promise rejected with reason ' + e.reason);

	e.preventDefault();
});

// this will now not throw an error to console
Promise.reject('An error occurred');

The unhandledrejection Event is Just for Monitoring

The unhandledrejection event is not the place to handle errors. It has been brought just to monitor and error-reporting. It is the developer's responsibility to see that an unhandled rejection should never be occurring in the application.

Browser Compatibility

As of writing this article, unhandledrejection event is supported in Chrome & Safari. Firefox and Edge are yet to implement it.

Here is a polyfill that can be used for the time being.

Useful Resources
What happens if we dont resolve or reject thepromise
unhandledrejection Event on MDN
rejectionhandled Event on MDN

In this Tutorial