| 2.再试试语法错误呢? window.onerror = function(message, source, lineno, colno, error) { console.log('捕获到异常:',{message, source, lineno, colno, error}); } let name = 'Jartto 
 控制台打印出了这样的异常: Uncaught SyntaxError: Invalid or unexpected token 
 什么,竟然没有捕获到语法错误? 3.怀着忐忑的心,我们最后来试试异步运行时错误: window.onerror = function(message, source, lineno, colno, error) { console.log('捕获到异常:',{message, source, lineno, colno, error}); } setTimeout(() => { Jartto; }); 
 控制台输出了: 捕获到异常: {message: "Uncaught ReferenceError: Jartto is not defined", source: "http://127.0.0.1:8001/", lineno: 36, colno: 5, error: ReferenceError: Jartto is not defined at setTimeout (http://127.0.0.1:8001/:36:5)} 
 4.接着,我们试试网络请求异常的情况: <script> window.onerror = function(message, source, lineno, colno, error) { console.log('捕获到异常:',{message, source, lineno, colno, error}); return true; } </script> <img src="./jartto.png"> 
 我们发现,不论是静态资源异常,,或者接口异常,错误都无法捕获到。 补充一点:window.onerror函数只有在返回true的时候,异常才不会向上抛出,否则即使是知道异常的发生控制台还是会显示Uncaught Error: xxxxx window.onerror = function(message, source, lineno, colno, error) { console.log('捕获到异常:',{message, source, lineno, colno, error}); return true; } setTimeout(() => { Jartto; }); 
 控制台就不会再有这样的错误了: Uncaught ReferenceError: Jartto is not defined at setTimeout ((index):36) 
 需要注意:
 onerror最好写在所有JS脚本的前面,否则有可能捕获不到错误;
 onerror无法捕获语法错误; 到这里基本就清晰了:在实际的使用过程中,onerror主要是来捕获预料之外的错误,而try-catch则是用来在可预见情况下监控特定的错误,两者结合使用更加高效。 问题又来了,捕获不到静态资源加载异常怎么办? 五、window.addEventListener当一项资源(如图片或脚本)加载失败,加载资源的元素会触发一个 Event接口的error事件,并执行该元素上的onerror()处理函数。这些error事件不会向上冒泡到window,不过(至少在Firefox中)能被单一的window.addEventListener捕获。 <scritp> window.addEventListener('error', (error) => { console.log('捕获到异常:', error); }, true) </script> <img src="./jartto.png"> 
 控制台输出: 
 由于网络请求异常不会事件冒泡,因此必须在捕获阶段将其捕捉到才行,但是这种方式虽然可以捕捉到网络请求的异常,但是无法判断 HTTP的状态是404还是其他比如500等等,所以还需要配合服务端日志才进行排查分析才可以。 需要注意: 
    不同浏览器下返回的 error对象可能不同,需要注意兼容处理。需要注意避免 addEventListener重复监听。 六、Promise Catch在 promise中使用catch可以非常方便的捕获到异步error,这个很简单。 (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |