JavaScript错误处理_异常捕获与监控系统

答案:通过结合try-catch、window.onerror和unhandledrejection,可全面捕获JavaScript同步异步错误,配合错误上报机制实现前端稳定性监控。

当JavaScript代码运行出错时,如果不加以处理,可能直接导致页面功能失效或用户体验中断。合理地捕获异常并建立监控系统,是保障前端稳定性的关键环节。

异常类型与try-catch基本用法

JavaScript中常见的错误类型包括SyntaxErrorReferenceErrorTypeError等。使用try-catch可以捕获同步代码中的运行时异常。

例如:

try {
  someUndefinedFunction();
} catch (error) {
  console.error('捕获到错误:', error.message);
}

注意:try-catch无法捕获异步任务中的错误,比如setTimeout内部抛出的异常。

window.onerror全局错误监听

通过监听window.onerror,可以捕获未被处理的JavaScript运行时错误,包括跨域脚本错误(需配合CORS和script标签的crossorigin属性)。

基本写法:

window.onerror = function(message, source, lineno, colno, error) {
  console.log('全局错误:', { message, source, lineno, error });
  // 上报到服务器
  reportErrorToServer({
    message: error?.message || message,
    stack: error?.stack,
    url: source,
    line: lineno,
    column: colno,
    timestamp: Date.now()
  });
  return true; // 阻止默认错误弹窗
};

该方法能捕获大部分同步错误,但对Promise异常无效。

unhandledrejection处理Promise异常

Promise执行过程中如果未加catch,会触发unhandledrejection事件。务必监听此事件,避免遗漏异步错误。

示例:

window.addEventListener('unhandledrejection', function(event) {
  const reason = event.reason;
  console.warn('未处理的Promise拒绝:', reason);

  reportErrorToServer({
    message: reason?.message || 'Unknown Promise rejection',
    stack: reason?.stack,
    type: 'unhandledrejection',
    timestamp: Date.now()
  });

  // 可选择阻止默认行为
  event.preventDefault();
});

这能有效覆盖async/await或链式调用中漏掉catch的情况。

错误上报与监控策略

收集错误后,需要将数据发送至监控服务。建议:

  • 使用navigator.sendBeacon发送错误日志,确保页面关闭时也能上报
  • 添加用户标识、页面URL、User-Agent等上下文信息
  • 限制上报频率,避免重复错误刷屏
  • 对敏感信息脱敏处理

简单上报函数:

function reportErrorToServer(data) {
  const payload = JSON.stringify(data);
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/log-error', payload);
  } else {
    fetch('/log-error', {
      method: 'POST',
      body: payload,
      keepalive: true
    }).catch(() => {});
  }
}

基本上就这些。关键是把try-catch、onerror、unhandledrejection三者结合,形成完整的异常捕获链条,并持续收集分析错误数据,及时发现线上问题。