js的各类错误捕获

一、前言

我们在开发中经常用到try catch来捕获接口错误,并上报到监控平台。这是你是否产生过疑问,这些错误在前端都是如何捕获到的?

二、常见错误类型

  • 解析时候发生语法错误
  • 值不是所期待类型
  • 引用为声明变量
  • 资源加载错误
  • Http请求错误

三、捕获错误

try catch

能够捕获常规运行时错误,语法错误或异步错误不行

// 常规运行时错误,可以捕获 ✅
try {
   
  console.log(notdefined);
} catch(e) {
   
  console.log( 捕获到异常: , e);
}

// 语法错误,不能捕获 ❌
try {
   
  const notdefined,
} catch(e) {
   
  console.log( 捕获到异常: , e);
}

// 异步错误,不能捕获 ❌
try {
   
  setTimeout(() => {
   
    console.log(notdefined);
  }, 0)
} catch(e) {
   
  console.log( 捕获到异常: ,e);
}

window.onerror

window.onerror,当 JS 运行时错误发生时,window 会触发一个 ErrorEvent 接口的 error 事件。

  • 监听错误
/**
* @param {String}  message    错误信息
* @param {String}  source    出错文件
* @param {Number}  lineno    行号
* @param {Number}  colno    列号
* @param {Object}  error  Error对象
*/

window.onerror = function(message, source, lineno, colno, error) {
   
   console.log( 捕获到异常: , {
   message, source, lineno, colno, error});
}
  • 捕获错误情况
// 常规运行时错误,可以捕获 ✅
window.onerror = function(message, source, lineno, colno, error) {
   
  console.log( 捕获到异常: ,{
   message, source, lineno, colno, error});
}
console.log(notdefined);

// 语法错误,不能捕获 ❌
window.onerror = function(message, source, lineno, colno, error
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值