简体   繁体   中英

Event.preventDefault does not seem to work (async context)

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" })

Verified on Firefox 76. Straight Promises don't work either. Looks like a bug. Probably should file an issue with Mozilla's Firefox tracker.
Note: this is not a solution. It's doubtful there is any solution except filing a bug and having it fixed.

 window.onerror = msg => console.log(msg) || false 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" })

Repro on Firefox97. It seems the error logs were printed on the console before triggering the 'unhandledrejection' handler so the event.preventDefault() could not help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM