🎯 前端监控的价值
前端监控是现代 Web 应用的眼睛。根据 Google 研究,53% 的用户会放弃加载超过 3秒 的页面。
可见性
了解真实用户的错误信息、性能体验
快速响应
错误发生 分钟级 发现并修复
数据驱动
基于真实数据优化用户体验
主动防御
发现问题于用户投诉之前
前端错误影响数据
- 88% 的用户遇到错误后会减少使用
- 70% 的用户会转向竞品
- 53% 的移动用户放弃 3 秒未加载的页面
- 每 1 秒延迟 导致转化率下降 7%
💡 独特观点
前端监控的真正价值不是"发现错误",而是理解用户真实体验。它需要模拟真实用户环境(设备、网络、浏览器),才能发现真问题。
🐛 错误捕获机制
错误捕获是前端监控的核心。需要捕获JavaScript 错误、资源加载错误、Promise 错误、接口错误等。
1. JavaScript 运行时错误
📝 全局错误捕获(window.onerror)
// 捕获 JavaScript 运行时错误
window.onerror = function(message, source, lineno, colno, error) {
// 构造错误信息
const errorInfo = {
message: message, // 错误消息
source: source, // 脚本 URL
lineno: lineno, // 行号
colno: colno, // 列号
error: error?.stack, // 错误堆栈
userAgent: navigator.userAgent,
timestamp: Date.now()
};
// 上报错误
reportError(errorInfo);
// 返回 true 阻止默认错误处理
return true;
};
// 示例:捕获未定义变量错误
function buggyFunction() {
const a = undefinedVar; // ReferenceError
}2. Promise 未捕获错误
📝 捕获未处理的 Promise 错误
// Promise 未捕获错误(Chrome 49+)
window.addEventListener('unhandledrejection', function(event) {
const errorInfo = {
message: event.reason?.message || String(event.reason),
stack: event.reason?.stack,
type: 'unhandledrejection',
timestamp: Date.now()
};
reportError(errorInfo);
// 可选:阻止默认错误处理
event.preventDefault();
});
// 示例:未捕获的 Promise 错误
async function fetchData() {
const response = await fetch('/api/data');
const data = await response.json();
return data;
}
// 调用但不捕获错误
fetchData(); // 如果失败,会触发 unhandledrejection3. 资源加载错误
📝 捕获资源加载失败(图片、脚本、样式)
// 捕获资源加载错误(使用事件委托)
document.addEventListener('error', function(event) {
const target = event.target;
// 只处理元素错误(非 JS 错误)
if (target !== window) {
const errorInfo = {
type: 'resource_error',
tagName: target.tagName,
src: target.src || target.href,
timestamp: Date.now()
};
reportError(errorInfo);
}
}, true); // 注意:使用捕获阶段
// 示例:图片加载失败
const img = document.createElement('img');
img.src = 'https://example.com/nonexistent.jpg';
img.onerror = function() {
console.log('图片加载失败');
};
document.body.appendChild(img);4. 接口请求错误
📝 拦截 Fetch/XHR 请求,捕获接口错误
// 拦截 Fetch API
const originalFetch = window.fetch;
window.fetch = function(...args) {
return originalFetch.apply(this, args)
.then(response => {
if (!response.ok) {
// HTTP 状态码不是 2xx
const errorInfo = {
type: 'http_error',
url: args[0],
method: args[1]?.method || 'GET',
status: response.status,
statusText: response.statusText,
timestamp: Date.now()
};
reportError(errorInfo);
}
return response;
})
.catch(error => {
// 网络错误(CORS、断网、超时)
const errorInfo = {
type: 'network_error',
url: args[0],
method: args[1]?.method || 'GET',
error: error.message,
timestamp: Date.now()
};
reportError(errorInfo);
throw error;
});
};
// 拦截 XMLHttpRequest(XHR)
const originalXHRSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(...args) {
this.addEventListener('error', function() {
const errorInfo = {
type: 'xhr_error',
url: this.responseURL,
method: this.method,
status: this.status,
timestamp: Date.now()
};
reportError(errorInfo);
});
return originalXHRSend.apply(this, args);
};📝 总结与展望
前端监控是保障用户体验的基础设施。通过本文的学习,你应该掌握了:
🎯 核心要点
- 错误捕获:window.onerror、unhandledrejection、资源错误、接口错误
- 性能监控:Core Web Vitals(LCP、FID、CLS)、Navigation Timing
- 用户行为:页面访问、点击事件、用户路径、会话录制
- 日志上报:立即上报、批量上报、空闲上报、丢失调优
- Source Map:上传 Source Map、错误堆栈还原、安全考虑
- Sentry:安装配置、Source Map 上传、Issue 管理、性能监控
- 自研方案:SDK 设计、后端存储(ClickHouse)、数据可视化
- 告警系统:告警规则、告警渠道(邮件、钉钉、Slack)、告警收敛
🚀 未来展望
前端监控领域正在快速演进,值得关注的方向:
- Real User Monitoring(RUM):真实用户性能监控(对比 Synthetic Monitoring)
- Session Replay:完整录制用户会话,复现错误场景
- AI 辅助诊断:自动分类错误、智能聚合、根因分析
- OpenTelemetry:统一可观测性标准(Tracing、Metrics、Logs)
- 边缘监控:Cloudflare Workers 边缘错误捕获