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', () => {})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值