js异常处理

错误处理方案

  • 不捕获,错误会一直向上抛

  • try&&catch&&finally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function sum(num1, num2) {
if (typeof num1 === 'number' && typeof num2 === 'number') {
return num1 + num2
}
throw new TypeError("the expected params is type of number")
}

try {
let res = sum(1, '3');
console.log(res);
} catch (err) {
// 模拟兜底处理
console.log(err.message);
console.log('错误上报');
} finally {
console.log('最终执行的代码');
}

throw

throw可以抛出的数据类型

  • 基本类型
1
throw 'error msg'
  • 对象类型
1
throw {code:-1,msg:'错误类型详细描述'}
  • 自定义类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MyError {
constructor(code, msg) {
this.code = code;
this.msg = msg;
}
}

function sum(num1, num2) {
if (typeof num1 === 'number' && typeof num2 === 'number') {
return num1 + num2
}
throw new MyError(-1, "the expected params is type of number")
}


try {
let res = sum(1, '2');
console.log(res);
} catch (err) {
console.log(err.code);
}
  • 错误类型
1
2
throw Error('Error desc');
throw TypeError('Type Error desc')

实例化的错误类型的属性

1
2
3
console.log(Object.getOwnPropertyDescriptors(new Error("the expected params is type of number")));
// srack 调用栈信息
// message 错误描述(参数)

Error的子类

  • TypeError:类型错误

  • RangeError:下标值越界

  • SyntaxError:语法错误

强调:

  • 如果抛出了异常,后续的代码都不会执行,抛出的错误需要在上层捕获并进行兜底处理。
  • 从ES10开始,catch的参数可以不用进行传递,开发者知道出现了了异常但是不用知道具体的异常信息,可以省略。
    1
    try { } catch { } finally { }