2026 年前端错误监控

错误监控是前端工程的必修课。

全局错误捕获

window.addEventListener("unhandledrejection", (event) => {
  console.error("未处理的 Promise 错误:", event.reason);
  fetch("/api/log-error", {
    method: "POST",
    body: JSON.stringify({
      message: event.reason?.message,
      stack: event.reason?.stack,
      url: window.location.href,
      userAgent: navigator.userAgent,
    }),
  });
});

React 错误边界

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error(error, info.componentStack);
  }
  render() {
    if (this.state.hasError) {
      return <h1>出错了,请刷新页面</h1>;
    }
    return this.props.children;
  }
}

Core Web Vitals 监控

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.name === "LCP") {
      console.log(`LCP: ${entry.startTime}ms`);
    }
  }
}).observe({ type: "largest-contentful-paint", buffered: true });