JavaScript and React course ยท Module 16: Error Handling and Suspense

Error Logging and Monitoring

5 min read ยท
In this lesson5

On a spacecraft, every failure is recorded in the black box. Without it, the crew couldn't analyze the causes of problems after the fact. In React applications, we have exactly the same problem -- if an error occurs for a user in production and we don't log it, we'll never know about it. Error logging and monitoring is your production black box.

Error Logging Strategies

In a production environment, we need several layers of logging:

1. console.error -- Only for Development

console.error is useful during local development, but in production the user doesn't see it, and you don't have access to it.

// Good for development, useless in production
componentDidCatch(error, errorInfo) {
  console.error('Error caught:', error);
  console.error('Component stack:', errorInfo.componentStack);
}

2. Logging to an External Service

In production, errors must be sent to a monitoring service:

class ErrorBoundary extends React.Component {
  componentDidCatch(error, errorInfo) {
    // Send to monitoring service
    logErrorToService({
      message: error.message,
      stack: error.stack,
      componentStack: errorInfo.componentStack,
      timestamp: new Date().toISOString(),
      url: window.location.href,
      userAgent: navigator.userAgent,
    });
  }

  // ...render with fallback
}

async function logErrorToService(errorData) {
  try {
    await fetch('/api/errors', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(errorData),
    });
  } catch (e) {
    // Fallback -- don't block the app if logging fails
    console.error('Failed to log error:', e);
  }
}

Sentry and Error Tracking Services

Sentry is the most popular service for monitoring errors in JavaScript and React applications. Other popular tools include LogRocket, Bugsnag, Datadog, and New Relic.

Basic Sentry Integration

import * as Sentry from '@sentry/react';

// Initialization in main/index.js
Sentry.init({
  dsn: 'https://key@sentry.io/project',
  environment: 'production',
  // Percentage of sessions to record (performance)
  tracesSampleRate: 0.2,
});

// Sentry automatically captures:
// - Unhandled exceptions
// - Unhandled Promise rejections
// - Network errors

Sentry with Error Boundary

import * as Sentry from '@sentry/react';

// Sentry provides a ready-made Error Boundary
function App() {
  return (
    <Sentry.ErrorBoundary
      fallback={({ error }) => (
        <div className="error-page">
          <h2>Something went wrong</h2>
          <p>The error has been automatically reported</p>
          <button onClick={() => window.location.reload()}>
            Refresh page
          </button>
        </div>
      )}
    >
      <SpaceStation />
    </Sentry.ErrorBoundary>
  );
}

Context and Breadcrumbs in Sentry

Sentry allows you to add context to errors -- information about the user, recent actions (breadcrumbs), and additional data:

// Set user context
Sentry.setUser({
  id: user.id,
  email: user.email,
  username: user.callsign,
});

// Manually add breadcrumbs (user action trail)
Sentry.addBreadcrumb({
  category: 'navigation',
  message: 'User navigated to mission panel',
  level: 'info',
});

// Manually report an error with additional context
Sentry.captureException(error, {
  extra: {
    missionId: currentMission.id,
    moduleState: moduleStatus,
  },
});

Custom Error Logging Hook

You can create your own hook that centralizes logging logic:

function useErrorLogger() {
  const logError = useCallback((error, context = {}) => {
    const errorReport = {
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString(),
      url: window.location.href,
      ...context,
    };

    // In production, send to the service
    if (process.env.NODE_ENV === 'production') {
      sendToErrorService(errorReport);
    }

    // In development, log to console
    console.error('[ErrorLogger]', errorReport);
  }, []);

  return { logError };
}

// Usage in a component
function MissionControl() {
  const { logError } = useErrorLogger();

  const handleDataFetch = async () => {
    try {
      const data = await fetchMissionData();
      setMissions(data);
    } catch (error) {
      logError(error, {
        component: 'MissionControl',
        action: 'fetchMissionData',
      });
      setError('Failed to fetch mission data');
    }
  };
}

Error Reporting in Production

Global Error Handlers

In addition to Error Boundaries and try-catch, it's worth adding global handlers that catch errors escaping other mechanisms:

// Global catching of uncaught errors
window.addEventListener('error', (event) => {
  logErrorToService({
    type: 'uncaught_error',
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
  });
});

// Global catching of unhandled Promise rejections
window.addEventListener('unhandledrejection', (event) => {
  logErrorToService({
    type: 'unhandled_rejection',
    message: event.reason?.message || 'Unknown rejection',
    stack: event.reason?.stack,
  });
});

Error Severity Levels

Not all errors are equally important. Error tracking services allow classification:

// Critical error - application is non-functional
Sentry.captureException(error, { level: 'fatal' });

// Error - functionality is broken, but app works
Sentry.captureException(error, { level: 'error' });

// Warning - something might be wrong
Sentry.captureMessage('API responding slowly', 'warning');

// Info - useful for debugging
Sentry.captureMessage('User changed language', 'info');

Source Maps for Production Debugging

Production code is minified -- the stack trace is unreadable without source maps. Source maps are like a decoding map -- they allow you to translate positions in minified code back to the original source files.

// Without source maps, the stack trace looks like:
// Error at e.render (main.a1b2c3.js:1:45678)

// With source maps:
// Error at MissionControl.render (MissionControl.jsx:42:15)

Source Maps Configuration

// webpack.config.js
module.exports = {
  devtool: 'source-map', // Generate source maps
  // ...
};

// Important: source maps should NOT be public!
// Upload them to Sentry, but don't serve them to users:
// sentry-cli sourcemaps upload ./build

Source maps allow you to see exactly which line of original code caused the error, even if the production bundle is minified into a single line. It's like having the technical blueprint of a spacecraft -- instead of looking at an incomprehensible minified panel, you see exactly which module failed and why. Remember, however, to never make source maps publicly available -- that would be like sharing the ship's blueprints with potential invaders.

Code for this lesson: App.jsx
import React, { useState, useCallback, useEffect } from 'react';
import './styles.css';

// Custom hook for logging errors
function useErrorLogger() {
  const [errorLog, setErrorLog] = useState([]);

  const logError = useCallback((error, context = {}) => {
    const report = {
      id: Date.now(),
      message: error.message || String(error),
      stack: error.stack ? error.stack.split('\n').slice(0, 3).join('\n') : 'none',
      timestamp: new Date().toLocaleTimeString(),
      url: window.location.href,
      ...context,
    };

    setErrorLog(prev => [report, ...prev].slice(0, 10));

    // In production we would send this to a service:
    // sendToSentry(report);
    console.error('[ErrorLogger]', report);
  }, []);

  return { logError, errorLog };
}

// Error Boundary with logging
class LoggingErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    // Logging to the "service"
    if (this.props.onError) {
      this.props.onError(error, {
        component: this.props.label || 'Unknown',
        type: 'render_error',
        componentStack: errorInfo.componentStack,
      });
    }
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-card">
          <strong>{this.props.label}: Failure</strong>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Retry
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Module that can throw an error
function UnstableModule({ name, failRate = 0.3 }) {
  if (Math.random() < failRate) {
    throw new Error(name + ': critical system failure!');
  }
  return (
    <div className="module-ok">
      <span className="dot green" /> {name}: Online
    </div>
  );
}

// Component with an async error
function DataPanel({ logError }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    try {
      await new Promise(r => setTimeout(r, 800));
      if (Math.random() > 0.5) {
        throw new Error('Database connection timeout');
      }
      setData({ missions: 42, crew: 7, fuel: '87%' });
    } catch (error) {
      logError(error, {
        component: 'DataPanel',
        action: 'fetchData',
        type: 'async_error',
      });
      setData(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="data-panel">
      <h3>Station data</h3>
      <button onClick={fetchData} className="fetch-btn">
        {loading ? 'Loading...' : 'Fetch data'}
      </button>
      {data && (
        <ul>
          <li>Missions: {data.missions}</li>
          <li>Crew: {data.crew}</li>
          <li>Fuel: {data.fuel}</li>
        </ul>
      )}
    </div>
  );
}

export default function App() {
  const { logError, errorLog } = useErrorLogger();
  const [key, setKey] = useState(0);

  // Global handler (simulation)
  useEffect(() => {
    const handler = (event) => {
      logError(new Error(event.reason?.message || 'Unhandled rejection'), {
        type: 'unhandled_rejection',
      });
    };
    window.addEventListener('unhandledrejection', handler);
    return () => window.removeEventListener('unhandledrejection', handler);
  }, [logError]);

  return (
    <div className="app">
      <h1>Error Logging & Monitoring</h1>
      <p className="subtitle">
        Every error is logged (black box)
      </p>
      <button onClick={() => setKey(k => k + 1)} className="reset-btn">
        Reset modules
      </button>

      <div className="modules" key={key}>
        <LoggingErrorBoundary label="Navigation" onError={logError}>
          <UnstableModule name="Navigation" />
        </LoggingErrorBoundary>

        <LoggingErrorBoundary label="Communication" onError={logError}>
          <UnstableModule name="Communication" />
        </LoggingErrorBoundary>

        <DataPanel logError={logError} />
      </div>

      <div className="log-panel">
        <h3>Error log ({errorLog.length})</h3>
        {errorLog.length === 0 ? (
          <p className="empty-log">No errors recorded</p>
        ) : (
          errorLog.map(entry => (
            <div key={entry.id} className="log-entry">
              <span className="log-time">{entry.timestamp}</span>
              <span className="log-type">[{entry.type || 'error'}]</span>
              <span className="log-msg">{entry.message}</span>
              {entry.component && (
                <span className="log-comp">({entry.component})</span>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why is console.error insufficient for monitoring errors in production?

  2. 2. How does Sentry integrate with Error Boundaries in React?

Hands-on tasks in the game

  • Vertical ordering

    Order error severity levels from highest to lowest:

  • Code editor

    Implement the useErrorLogger hook

  • Click in order

    Click elements in order for building error logging in componentDidCatch:

  • Horizontal ordering

    Arrange the correct syntax for a global Promise rejection handler:

  1. Questionconsole.error in Production
  2. Put in orderError Severity Levels
  3. Coding taskPractice: Custom useErrorLogger Hook
  4. QuestionSentry and Error Boundary
  5. Click in orderLogging Errors in componentDidCatch
  6. Put in orderGlobal unhandledrejection Handler

Useful articles