繁体   English   中英

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

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

我们可以像这样存根任何 function 或 class,

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

与此类似,有什么方法可以拦截“throw”语句。 这样无论整个网站抛出什么异常,都可以在一个地方处理吗?

这还不能满足你的需求吗? 您需要监听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