前端监控实践:错误、性能与用户行为追踪
为什么需要前端监控
生产环境崩溃往往难以被及时发现,导致开发团队一无所知。有效的监控能避免被动等待用户反馈。
反面案例
// 反面案例:没有监控
// components/Checkout.jsx
export default function Checkout() {
const [loading, setLoading] = useState(false);
const handleSubmit = async () => {
setLoading(true);
try {
await api.checkout();
} catch (error) {
console.error('Checkout failed:', error);
setError('支付失败');
} finally {
setLoading(false);
}
};
return (
<button onClick={handleSubmit} disabled={loading}>
{loading ? '支付中...' : '支付'}
</button>
);
}
错误仅在控制台打印,开发团队无法感知,用户遇到问题只能截图反馈。
正确实践
1. 错误监控
// 正确实践:Sentry 错误监控
// src/utils/errorMonitoring.js
import * as Sentry ;
() {
.({
: ,
: [
.(),
.()
],
: ,
:
});
}
() {
.(error);
}
() {
.(message);
}

