【四】性能优化&前端监控_页面错误的监控

85 阅读1分钟

错误监控

JS 中的错误监控分为下面 3 类

  1. 资源加载错误
  2. js 错误
  3. promise 错误

资源加载错误

页面中资源加载错误,我们可以通过 监听 error 错误来实现捕获

监听核心代码:

window.addEventListener(
  'error',
  (e) => {
    const { target } = e;
    const tag = target.tagName;
    const url = target.src || target.href;
    console.log(`捕获到了加载错误, 加载标签类型为 ${tag}; 资源 url 为 ${url}`);
  },
  // 错误的监听必须在捕获的时候进行监听
  true
);

demo: 6_资源加载错误

error_source.png

js 错误

对于 js 中的执行错误,我们可以通过 window.onerror 来监听

监听的核心代码:

window.onerror = (message, source, lineno, colno, error) => {
  console.log('捕获到异常:', { message, source, lineno, colno, error });
};

demo: 7_js 中的执行错误

js_error.png

注意点:

  1. 如果你的代码中存在语法错误,则 onerror 是监听不到的!例如我们上述的 demo 中修改了 const 变量的赋值,但是并不没有捕获到这个错误

promise 错误

对于未处理的 promise 错误,我们可以监听 unhandledrejection 错误

监听的核心代码:

window.addEventListener('unhandledrejection', (e) => {
  console.log('e: ', e);
});

demo: 8_promise 错误

promise_error.png

React 框架错误的采集

react 错误采集使用 React 提供的 ErrorBoundary 即可,可阅读下面的资料: Displaying an error to users with a error boundary

参考链接

系列&demo 相关

  1. github blog
  2. demos 仓库
  3. 浏览器渲染流程
  4. 测试 url - ieubs
  5. 测试 url - 交易猫

参考资料

  1. 深入了解前端监控原理
  2. 前端监控 SDK 的一些技术要点原理分析
  3. 腾讯二面:现在要你实现一个埋点监控 SDK,你会怎么设计?
  4. Displaying an error to users with a error boundary