JS 异常处理
try 语句使您能够测试代码块中的错误。
catch 语句允许您处理错误。
throw 语句允许您创建自定义错误 抛出异常(error对象包含name和message属性)。
finally 使您能够执行代码,在 try 和 catch 之后,无论结果如何。
try{
代码块 throw xxx
}catch(err){
处理异常
}finally{
总是执行的代码块
}
finally 使用场景:文件操作在 finally 关闭文件
Error 对象 类型
| EvalError | 已在 eval() 函数中发生的错误(旧版js) |
| RangeError | 数值变量或参数超出其有效范围 |
| ReferenceError | 无效引用 |
| SyntaxError | 语法错误 |
| TypeError | 变量或参数不属于有效类型 |
| URIError | 给 encodeURI() 或 decodeURI() 传递的参数无效 |
| AggregateError | 由一个操作产生且需要报告的多个错误 如:Promise.any() |
| DOMException | |
| DOMError |
Error 实例属性方法
| Error.prototype.message | 错误消息。对于用户创建的 Error 对象,这是构造函数的第一个参数提供的字符串。 |
| Error.prototype.name | 错误名称。这是由构造函数决定的。 |
| Error.prototype.cause (en-US) | 表示导致当前错误被抛出的原因——通常是另一个错误。对于用户创建的 Error 对象,这是构造函数的第二个参数提供的值。 |
| Error.prototype.toString() | 返回表示该对象的字符串。覆盖了 Object.prototype.toString() 方法。 |
throw new Error(message, fileName, lineNumber)
class CustomError extends Error {
constructor(foo = 'bar', ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params);
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
// Custom debugging information
this.foo = foo;
this.date = new Date();
}
}
try {
throw new CustomError('baz', 'bazMessage');
}
处理未捕获异常
浏览器
window.onerror()
绑定 onerror 事件
Node.js
process.on('uncaughtException', () => {})
process.on('unhandledRejection', () => {})
内容会不断更新,欢迎批评指正。

浙公网安备 33010602011771号