zhuber
zhuber

Reputation: 5524

Global unhandled rejection handler

I'm using https://github.com/rtsao/browser-unhandled-rejection for global unhandled rejections.

This is how handler is registered:

window.addEventListener('unhandledrejection', (params) => {

});

I'm not sure how should I handle promise in this callback? Everything is working correctly and this handler is invoked every time promise fails and catch is not implemented so I'm getting 'Uncaught (in promise)'.

Is there a way to handle failed promise inside unhandledrejection so it does not throw 'Uncaught (in promise)' error and that code where promise failed continue normally as if catch was implemented? In params argument I have access to rejected promise but I'm not sure how should I handle that or is it even possible?

Upvotes: 1

Views: 1496

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

According to the specification, the event is cancellable, so you can add

params.preventDefault(); // Note: `params` here is more idiomatically called `event`

to your handler to prevent the default action. (This prevents the "Unhandled rejection" warning on Chrome, which implements this without that polyfill.)

Example without preventDefault:

window.addEventListener("unhandledrejection", event => {
    console.log("Got the unhandledrejection event");
});
Promise.reject();
Look in the real browser console.

Example with preventDefault:

window.addEventListener("unhandledrejection", event => {
    console.log("Got the unhandledrejection event");
    event.preventDefault();
});
Promise.reject();
Look in the real browser console.

Upvotes: 2

Related Questions