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', () => {})
内容会不断更新,欢迎批评指正。
分类:
# JavaScript
标签:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南