Error monitoring in React requires catching errors at all levels (render, async, event handlers) and sending them to an analytics service.
System design context: Error monitoring must cover three categories:
Sentry integration:
1// sentry.client.config.ts2import * as Sentry from "@sentry/react";34Sentry.init({5 dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,6 integrations: [7 Sentry.browserTracingIntegration(),8 Sentry.replayIntegration({ maskAllText: true })9 ],10 tracesSampleRate: 0.1, // 10% of transactions11 replaysSessionSampleRate: 0.01,12 replaysOnErrorSampleRate: 1.0 // 100% of error replays13});
Global Error Boundary:
1import { ErrorBoundary } from "@sentry/react";23function ErrorPage() {4 return (5 <div className="min-h-screen flex items-center justify-center">6 <div className="text-center">7 <h1 className="text-2xl font-bold mb-2">Something went wrong</h1>8 <p className="text-gray-600 mb-4">We have been notified and are working on a fix.</p>9 <button onClick={() => window.location.reload()}>Try again</button>10 </div>11 </div>12 );13}1415function App() {16 return (17 <ErrorBoundary18 fallback={<ErrorPage />}19 onError={(error, componentStack) => {20 Sentry.withScope((scope) => {21 scope.setExtras({ componentStack });22 Sentry.captureException(error);23 });24 }}25 >26 <Router />27 </ErrorBoundary>28 );29}
Catching unhandled errors (all three categories):
1// 1. Unhandled promise rejections2useEffect(() => {3 const errorHandler = (event: PromiseRejectionEvent) => {4 Sentry.captureException(event.reason);5 };6 window.addEventListener("unhandledrejection", errorHandler);7 return () => window.removeEventListener("unhandledrejection", errorHandler);8}, []);910// 2. Event handler errors11function RiskyButton() {12 const handleClick = () => {13 try {14 doSomethingRisky();15 } catch (error) {16 Sentry.captureException(error);17 showErrorToast("Something went wrong. Please try again.");18 }19 };20 return <button onClick={handleClick}>Risky action</button>;21}2223// 3. Async operation errors24function DataFetcher() {25 useEffect(() => {26 fetch("/api/data")27 .then(res => res.json())28 .catch(error => {29 Sentry.captureException(error);30 showErrorToast("Failed to load data");31 });32 }, []);33 return null;34}
Adding user context for debugging:
1Sentry.setUser({2 id: user.id,3 email: user.email,4 role: user.role5});67Sentry.setTags({8 environment: process.env.NODE_ENV,9 feature_flag: "new_checkout"10});
What to track:
unhandledrejection event listener.fetch or axios error responses.Production pitfalls:
tracesSampleRate.Monitoring: Set up Sentry alerts for error rate spikes, new error types, and performance regressions. Use dashboards to track error trends over time.