I realise there are a few questions about preventDefault
not working. But my question is about the rather straightforward case where you have an async
function and an error is thrown:
throw 'error of some kind';
... and then you want to have a "mopping up" function to catch any and all such errors. This then works as expected:
window.addEventListener('unhandledrejection', function (event) {
console.log( 'unhandled Promise rejection, event: ', event );
// event.preventDefault();
});
But if I uncomment the event.preventDefault()
, I expect to see the throw
message not then get printed as an error to console. But it always does get so printed.
I checked to make sure that event
is indeed cancelable
in this case. It claims to be so.
PS from my experiments it seems to be that
window.onunhandledrejection = event => {
...
};
is just another way of implementing this same listener for this same "unhandledrejection" event. Using event.preventDefault()
there doesn't seem to work either.
Edit
After a few experiments I seem to find that the only way I can find to prevent this is to swallow the error (using try...catch
) at some point, preferably at the highest async
call in the stack (or rather in the sequence of calls of async
functions), if that can be determined.
window.addEventListener('unhandledrejection', event => {
console.log(event.cancelable, event.reason, "unhandled rejection")
event.preventDefault()
event.stopPropagation()
event.stopImmediatePropagation()
return false
})
async function x() {
console.log('async')
throw "async error"
}
x()
new Promise(res => {
console.log('prom')
throw "prom error"
})