简体   繁体   English

有没有办法在香草 javascript 中存根/拦截 javascript 语句“抛出”?

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

We can stub any function or class like this,我们可以像这样存根任何 function 或 class,

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.与此类似,有什么方法可以拦截“throw”语句。 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您需要监听error事件,按照您想要的方式处理它并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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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