简体   繁体   中英

Is there a way to stub/intercept a javascript statement 'throw' in vanilla javascript?

We can stub any function or class like this,

class ErrorStub{
        constructor(message){
                // do whatever with 'message'
        }
}
Error = ErrorStub
new Error('This will go to ErrorStub now')

Similar to this, is there any way we can intercept a 'throw' statement. So that whatever exception is thrown across whole website, can be handled in one place?

Wouldn't this satisfy your needs? You would need to listen to the error event, handle it the way you want and return false

 function interceptError(exception) { // Here you can write code which intercepts before // the error gets triggered and printed in the console alert(`Exception occured: ${exception.message}`) } window.addEventListener("error", function (e) { interceptError(e); return false; }) throw new Error('Test exception');

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