|
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
(编辑:PHP编程网 - 金华站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|