项目开发中,如何实现前端错误监控系统,保证应用的稳定性?
前端错误监控系统实现方案分为六个核心步骤:
一、错误捕获机制
JavaScript运行时错误捕获
window.addEventListener('error', (event) => {
const { message, filename, lineno, colno, error } = event
reportError({
type: 'JS_ERROR',
message,
stack: error?.stack,
file: filename,
line: lineno,
column: colno
})
})
Promise未捕获异常
window.addEventListener('unhandledrejection', (event) => {
reportError({
type: 'PROMISE_ERROR',
reason: event.reason?.message || event.reason,
stack: event.reason?.stack
})
})
资源加载错误(需设置捕获阶段)
window.addEventListener('error', (e) => {
if (e.target.tagName === 'IMG' || e.target.tagName === 'SCRIPT') {
reportError({
type: 'RESOURCE_ERROR',
src: e.target.src,
tagName: e.target.tagName
})
}
}, true)
二、错误信息采集维度
三、上报策略优化
优先传输:使用navigator.sendBeacon()保证页面关闭时可靠传输
function sendData(data) {
if (navigator.sendBeacon) {
const blob = new Blob([JSON.stringify(data)], {type: 'application/json'})
navigator.sendBeacon('/log-endpoint', blob)
} else {
new Image().src = `/log-endpoint?data=${encodeURIComponent(JSON.stringify(data))}`
}
}
四、服务端处理架构
五、智能分析系统
六、框架集成方案
React错误边界
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
reportError({
type: 'REACT_ERROR',
error: error.toString(),
componentStack: info.componentStack
})
}
}
Vue错误处理器
Vue.config.errorHandler = (err, vm, info) => {
reportError({
type: 'VUE_ERROR',
message: err.message,
component: vm.$options.name,
lifecycle: info
})
}
生产环境注意事项:
推荐技术栈组合:
https://juejin.cn/post/6862559324632252430