JS原生错误 除了try catch中捕获住的错误,我们还需要上报没有被捕获住的错误——通过error事件和unhandledrejection事件去监听。

JS原生错误
除了try catch中捕获住的错误,我们还需要上报没有被捕获住的错误——通过error事件和unhandledrejection事件去监听。

错误报警三类监控;首先是js、最后是react、vue的项目

js error事件

error事件是用来监听DOM操作错误DOMException和JS错误告警的,具体来说,JS错误分为下面8类

  1. InternalError: 内部错误,比如如递归爆栈;
  2. RangeError: 范围错误,比如new Array(-1);
  3. EvalError: 使用eval()时错误;
  4. ReferenceError: 引用错误,比如使用未定义变量;
  5. SyntaxError: 语法错误,比如var a = ;
  6. TypeError: 类型错误,比如[1,2].split(‘.’);
  7. URIError: 给 encodeURI或 decodeURl()传递的参数无效,比如decodeURI(‘%2’)
  8. Error: 上面7种错误的基类,通常是开发者抛出

也就是说,代码运行时发生的上述8类错误,都可以被检测到。

unhandledrejection

Promise内部抛出的错误是无法被error捕获到的,这时需要用unhandledrejection事件。

// 初始化错误监控
  initError(){
    window.addEventListener('error', event=>{
      this.error(error);
    })
    window.addEventListener('unhandledrejection', event=>{
      this.error(new Error(event.reason), { type: 'unhandledrejection'})
    })
  }

React/Vue组件错误

成熟的框架库都会有错误处理机制,React和Vue也不例外

React的错误边界

它的使用很简单,就是一个带有特殊生命周期的类组件,用它把业务组件包裹起来。

这两个生命周期是getDerivedStateFromErrorcomponentDidCatch

// 定义错误边界
class ErrorBoundary extends React.Component {
  state = { error: null }
  static getDerivedStateFromError(error) {
    return { error }
  }
  componentDidCatch(error, errorInfo) {
    // 调用我们实现的SDK实例
    insSDK.error(error, errorInfo)
  }
  render() {
    if (this.state.error) {
      return <h2>Something went wrong.</h2>
    }
    return this.props.children
  }
}
...
<ErrorBoundary>
  <BuggyCounter />
</ErrorBoundary>

Vue的错误边界

vue也有一个类似的生命周期来做这件事,不再赘述:errorCaptured

Vue.component('ErrorBoundary', {
  data: () => ({ error: null }),
  errorCaptured (err, vm, info) {
    this.error = `${err.stack}\n\nfound in ${info} of component`
    // 调用我们的SDK,上报错误信息
    insSDK.error(err,info)
    return false
  },
  render (h) {
    if (this.error) {
      return h('pre', { style: { color: 'red' }}, this.error)
    }
    return this.$slots.default[0]
  }
})
...
<error-boundary>
  <buggy-counter />
</error-boundary>


结束

以上是js常见错误三类错误监控

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员斯文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值