如何追踪javascript错误_有哪些线上监控方案?

线上JavaScript错误需主动捕获:用window.onerror捕获同步错误,unhandledrejection补异步错误,error事件捕获资源加载失败,并通过sendBeacon上报、去重、采样与脱敏保障监控可用。

线上 JavaScript 错误必须主动捕获,靠用户反馈或日志排查已经太晚——90% 的前端崩溃在首次上报后 2 小时内就能定位修复,前提是监控链路完整且数据可用。

window.onerror 捕获同步运行时错误

这是最基础、覆盖最广的错误入口,能拿到语法错误(如 Unexpected token)、执行异常(如 Cannot read property 'x' of undefined)等。但注意它不捕获 Promise 异常,也不暴露跨域脚本的堆栈细节。

  • window.onerror 回调接收 5 个参数:messagesourcelinenocolnoerror;优先用 error?.stack,比 message 更准
  • 跨域脚本报错会显示为 "Script error.",必须同时满足两个条件才能解封:① ;② 服务端返回 Access-Control-Allow-Origin: *
  • 返回 true 可阻止错误冒泡到控制台(仅用于调试屏蔽,生产环境慎用)
window.onerror = function(message, source, lineno, colno, error) {
  reportError({
    type: 'js_error',
    message: error?.message || message,
    stack: error?.stack,
    file: source,
    line: lineno,
    column: colno,
    url: location.href
  });
  return true;
};

window.addEventListener('unhandledrejection') 补全异步错误

Promise 拒绝若没被 catch,会静默失败,window.onerror 完全无感知。这个事件是唯一可靠方式,尤其在 Axios 请求、async/await 场景中高频出现。

  • event.reason 可能是 Error 对象、字符串,甚至 undefined,需做类型判断再取 stacktoString()
  • 某些 Promise polyfill(如 es6-promise)可能劫持原生事件,建议在 polyfill 加载前注册监听
  • 不要只记录 reason,补上当前路由、用户操作路径(如 location.pathname + '?step=submit'),否则无法复现
window.addEventListener('unhandledrejection', function(event) {
  const reason = event.reason;
  reportError({
    type: 'unhandledrejection',
    reason: reason?.stack || reason?.toString() || 'unknown',
    url: location.href,
    route: location.pathname
  });
});

window.addEventListener('error', true) 捕获资源加载失败

图片 404、CDN 脚本加载超时、CSS 解析失败……这些不会触发 JS 报错,但会导致白屏、样式错乱、功能缺失。必须通过全局 error 事件捕获,并用捕获阶段(第三个参数设为 true)确保能收到子元素错误。

  • 只处理 event.target 等资源节点,过滤掉 window 层级的重复触发
  • 记录 event.target.srcevent.target.href,结合 performance.getEntriesByName() 查加载耗时,快速区分是网络问题还是资源本身不存在
  • 动态插入的资源(如懒加载图片)也要手动绑定 onerror,不能只依赖全局监听
window.addEventListener('error', function(event) {
  const target = event.target;
  if (target instanceof HTMLImageElement || target instanceof HTMLScriptElement) {
    reportError({
      type: 'resource_error',
      url: target.src || target.href,
      tagName: target.tagName.toLowerCase(),
      timestamp: Date.now()
    });
  }
}, true);

上报策略决定监控是否真正可用

错误收集只是第一步,上报失控会让监控本身成为性能瓶颈甚至故障源。真实线上环境里,80% 的“监控失效”源于上报逻辑写得太糙。

  • 强制用 navigator.sendBeacon() 发送,避免页面跳转/关闭时丢日志;fallback 到 localStorage 缓存(最多存 20 条),下次打开补传
  • 错误去重靠“指纹”,不是简单比对 message,而是用 type + stack.split('\n')[0] 生成哈希,1 秒内相同指纹只报一次
  • 大流量站点必须采样,比如 error 全量上报,warn 级别按 sampleRate: 0.05 控制;监控 SDK 自身代码要用 try/catch 包裹,禁止因埋点出错拖垮业务

最容易被忽略的一点:所有上报字段必须脱敏。URL 参数、localStorage 快照、用户输入值……只要含手机号、token、身份证片段,一律替换为 [REDACTED],否则监控系统反而成安全漏洞出口。