# 容错

首先看这样一个demo

demo0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>容错</title>
</head>
<body>
    <script>
        error;
        console.log(1);
    </script>
    <script>
        console.log(2);
    </script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

此时运行会爆红,但是2会输出,因为在不同的代码块 那么如何捕获错误,不让出现红

# try...catch

demo1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>容错</title>
</head>
<body>
    <script>
        try {
            error;
        } catch {
            console.log(1);
        }
    </script>
    <script>
        console.log(2);
    </script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

看到可以捕获到我们刚才使用未定义变量的错误,没有爆红 但是try..catch什么都能捕获吗 并不是 如果语法编译错误了怎么办,比如错误的标点符号,就会爆红 try..catch无法捕捉语法错误

try {
            error;
        } catch {
            console.log(1);
        }
1
2
3
4
5

try..catch也无法捕捉异步错误

        try {
            setTimeout(() => {
                error;
            }, 1000);
        } catch(err) {
            console.log(err);
        }
1
2
3
4
5
6
7

语法错误要靠lint来去除 那么异步错误怎么办

# window.onerror

window.onerror = function(msg, url, row, col, error) {
            console.log('我知道错误了');
            return true;
        }
        try {
            setTimeout(() => {
                error
            }, 1000);
        } catch (err){
            console.log(err);
        }
1
2
3
4
5
6
7
8
9
10
11

try catch 捕获意料之内的错误 onerror捕获意料之外的错误 在用onerror时,要return true,否则会捕获到但是会继续爆红

# 捕获404错误

当cdn挂了时,找不到资源的报错 这种报错阻止不了,属于网络级的错误,只能监听到错误,然后赶快去修

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>容错</title>
</head>
<body>
    <img src="./404.png"/>
    <script>
        window.addEventListener('error', (msg, url, row, col, error) => {
            console.log('404错误');
            return false;
        }, true)
    </script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 捕获promise错误

        window.addEventListener('unhandledrejection', function(e) {
            e.preventDefault();
            console.log(e.reason);
        })
        new Promise((resolve, reject) => {
            reject('promise错误');
        })
1
2
3
4
5
6
7

# 捕获iframe错误

window.frames[0].onerror = function() {}
1