0%
错误处理方案
不捕获,错误会一直向上抛
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 {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")));
|
Error的子类
TypeError:类型错误
RangeError:下标值越界
SyntaxError:语法错误
强调:
- 如果抛出了异常,后续的代码都不会执行,抛出的错误需要在上层捕获并进行兜底处理。
- 从ES10开始,catch的参数可以不用进行传递,开发者知道出现了了异常但是不用知道具体的异常信息,可以省略。
1
| try { } catch { } finally { }
|