前端容错

前端容错异常处理方式的总结

切分不同的脚本独立运行

1
2
3
4
5
6
7
<script>
xxx
console.log(1)
</script>
<script>
console.log(2)
</script>

第二个脚本正常运行,不会受第一个脚本影响

try catch

  • try不能检测到语法错误,语法解析错误是捕获不了的,onerror也不行

    1
    2
    3
    4
    5
    6
    try{
    var error = 'error'
    } catch (e){
    console.log("检测不到中文分号")
    console.log(e)
    }
  • try检测不到异步中的错误

    1
    2
    3
    4
    5
    6
    7
    8
    try {
    setTimeout(()=>{
    error
    })
    } catch(e){
    console.log("检测不到setTimeout中的错误")
    console.log(e)
    }

window.onerror

onerror用来捕捉预料之外的错误,而try-catch用来在可预见情况下监控特定的错误,两者组合使用更加高效
window.onerror只有在函数返回true的时候,异常才不会向上抛出,否则即使知道异常的发生控制台还是会显示错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.onerror = function (message, source, lineno, colno, error) {
console.log("检测到setTimeout里的错误")
console.log({
message,
source,
lineno,
colno,
error
})
return true;
};
setTimeout(()=>{
error
})

监听error

由于网络请求异常不会事件冒泡,因此必须在捕获阶段将其捕捉到,这种方式虽然可以捕捉到网络请求的异常,但是无法判断http的状态(404,500等等),所以还需要配合服务端日志进行排查分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<body>
<img src="./404.jpg">
</body>
<script>
document.addEventListener('error', function (message, source, lineno, colno, error) {
console.log({
message,
source,
lineno,
colno,
error
})
return true;
}, true)
</script>

unhandledrejection 处理 Promise 的异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.addEventListener("unhandledrejection",function(e){
e.preventDefault()
console.log("全局捕获promise error")
console.log(e.reason)
return true;
})
Promise.reject("promise error")
new Promise((resolve,reject)=>{
reject('promise error')
})
new Promise((resolvet)=>{
resolve()
}).then(()=>{
throw 'promise error'
})