错误监控
JS 中的错误监控分为下面 3 类
- 资源加载错误
- js 错误
- 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_资源加载错误
js 错误
对于 js 中的执行错误,我们可以通过 window.onerror 来监听
监听的核心代码:
window.onerror = (message, source, lineno, colno, error) => {
console.log('捕获到异常:', { message, source, lineno, colno, error });
};
demo: 7_js 中的执行错误
注意点:
- 如果你的代码中存在语法错误,则 onerror 是监听不到的!例如我们上述的 demo 中修改了 const 变量的赋值,但是并不没有捕获到这个错误
promise 错误
对于未处理的 promise 错误,我们可以监听 unhandledrejection 错误
监听的核心代码:
window.addEventListener('unhandledrejection', (e) => {
console.log('e: ', e);
});
demo: 8_promise 错误
React 框架错误的采集
react 错误采集使用 React 提供的 ErrorBoundary 即可,可阅读下面的资料: Displaying an error to users with a error boundary