JavaScript and React course ยท Module 11: Data Fetching and APIs

Advanced Error Handling

6 min read ยท
In this lesson4

In space, things often don't go according to plan: communication can be interrupted, servers can be overloaded, data can be corrupted. Until now every error ended with a single message along the lines of "Something went wrong". The user then doesn't know whether to log in, wait or check the Wi-Fi. Good error handling is the difference between a successful mission and a disaster. In this lesson we'll build four layers of protection: clear messages, an Error Boundary, toast notifications and retrying with a growing delay.

Try/Catch/Finally - The Full Pattern

The first layer turns HTTP status codes into sentences a human understands. A switch statement picks the message for each code, and catch tells server errors apart from network errors. When there's no connection at all, fetch() rejects its Promise with a TypeError:

async function fetchWithFullErrorHandling(url) {
  try {
    // Attempt to fetch data
    const response = await fetch(url);

    if (!response.ok) {
      // Different messages for different error codes
      switch (response.status) {
        case 400:
          throw new Error('Invalid request');
        case 401:
          throw new Error('Unauthorized - please log in');
        case 403:
          throw new Error('Access denied to this resource');
        case 404:
          throw new Error('Resource not found');
        case 429:
          throw new Error('Too many requests - try again later');
        case 500:
          throw new Error('Server error - try again later');
        default:
          throw new Error(`Unknown error: ${response.status}`);
      }
    }

    return await response.json();
  } catch (err) {
    // Handle network errors (no internet, timeout)
    if (err instanceof TypeError) {
      throw new Error(
        'Network error - check your internet connection'
      );
    }
    throw err; // Re-throw other errors
  }
}

Our own errors from the switch are plain Error objects, not TypeError, so catch passes them on unchanged (throw err). The function still returns data or throws an error, only the quality of the message has changed.

ErrorBoundary Component

The second layer protects against an error that would blow up the whole interface. When a component throws during rendering, React unmounts the whole tree and the user sees a blank page. An Error Boundary is a component that catches rendering errors in its children and shows a fallback view. Even in React 19 it can only be written as a class component, because it needs the lifecycle methods static getDerivedStateFromError (sets the error state) and componentDidCatch (for example, logs the error):

import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error, errorInfo) {
    console.error('ErrorBoundary caught an error:', error);
    console.error('Stack:', errorInfo.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-boundary">
          <h2>Something went wrong</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({
            hasError: false, error: null
          })}>
            Try again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// Usage:
function App() {
  return (
    <ErrorBoundary>
      <SpaceDashboard />
    </ErrorBoundary>
  );
}

When SpaceDashboard blows up, the rest of the app survives, and the button clears the state and tries to render the children again. A very important limitation from the React docs: an Error Boundary does not catch errors in event handlers or in asynchronous code, such as a rejected fetch() inside useEffect. You handle those with try/catch and an error state. In practice I recommend the ready-made react-error-boundary package so you don't have to write this class yourself.

Toast Notifications

The third layer is messages that don't cover the content. A toast is a short bubble in the corner of the screen that disappears after a few seconds. So that any component can trigger one, we expose an addToast function through Context:

import React, { useState, createContext, useContext } from 'react';

const ToastContext = createContext();

function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);

  const addToast = (message, type = 'error') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    // Auto-remove after 5 seconds
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 5000);
  };

  return (
    <ToastContext.Provider value={{ addToast }}>
      {children}
      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

function useToast() {
  return useContext(ToastContext);
}

The provider keeps the list of toasts in state, and setTimeout removes each one after 5 seconds. The useToast hook is just a shortcut to useContext. Now any component inside the provider can report a success or an error:

// Usage in a component:
function DataComponent() {
  const { addToast } = useToast();

  const fetchData = async () => {
    try {
      const response = await fetch('/api/data');
      if (!response.ok) throw new Error('Server error');
      const data = await response.json();
      addToast('Data fetched successfully!', 'success');
    } catch (err) {
      addToast(err.message, 'error');
    }
  };

  return <button onClick={fetchData}>Fetch data</button>;
}

The component doesn't render any message itself, it only reports it upward. A small detail: Date.now() as an id can repeat for two toasts in the same millisecond, so in production use crypto.randomUUID() or a counter.

Retry with Exponential Backoff

The fourth layer fixes temporary errors. When the server is overloaded (429) or failing (5xx), retrying immediately only makes things worse. Exponential backoff means waiting longer and longer: 1 s, 2 s, 4 s. We compute the delay as Math.pow(2, attempt) * 1000:

async function fetchWithRetry(url, maxRetries = 3) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url);

      if (response.status === 429 || response.status >= 500) {
        // Server overloaded or server error
        if (attempt < maxRetries) {
          // Exponential backoff: 1s, 2s, 4s
          const delay = Math.pow(2, attempt) * 1000;
          console.log(
            `Attempt ${attempt + 1} failed. \
Retrying in ${delay}ms...`
          );
          await new Promise(resolve =>
            setTimeout(resolve, delay)
          );
          continue;
        }
      }

      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }

      return await response.json();
    } catch (err) {
      if (attempt === maxRetries) {
        throw new Error(
          `Failed after ${maxRetries + 1} attempts: ${err.message}`
        );
      }

      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

With maxRetries = 3 the function tries four times in total, and after the last failure it throws an error with the number of attempts. Note that catch retries every error, including a 404, where retrying achieves nothing. In a real project retry only network errors, 429 and 5xx, and TanStack Query from the previous lesson will do it for you (three retries with backoff by default).

Remember: a good error message tells the crew what happened and what they can do next, so never leave them in the dark.

Code for this lesson: App.jsx
import React, { useState, createContext, useContext } from 'react';

// Toast Context
const ToastContext = createContext();

function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);

  const addToast = (message, type = 'error') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 4000);
  };

  const removeToast = (id) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  };

  return (
    <ToastContext.Provider value={{ addToast }}>
      {children}
      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={"toast toast-" + toast.type}>
            <span>{toast.message}</span>
            <button className="toast-close" onClick={() => removeToast(toast.id)}>x</button>
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

function useToast() {
  return useContext(ToastContext);
}

// Simulation of different server responses
function simulateResponse(scenario) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      switch (scenario) {
        case 'success':
          resolve({ ok: true, status: 200, json: () => Promise.resolve({ data: 'Data fetched!' }) });
          break;
        case '404':
          resolve({ ok: false, status: 404, statusText: 'Not Found' });
          break;
        case '500':
          resolve({ ok: false, status: 500, statusText: 'Internal Server Error' });
          break;
        case 'network':
          reject(new TypeError('Failed to fetch'));
          break;
        default:
          resolve({ ok: true, status: 200 });
      }
    }, 1000);
  });
}

function ErrorDemo() {
  const { addToast } = useToast();
  const [loading, setLoading] = useState(false);

  const testScenario = async (scenario) => {
    setLoading(true);
    try {
      const response = await simulateResponse(scenario);

      if (!response.ok) {
        switch (response.status) {
          case 400: throw new Error('Invalid request');
          case 401: throw new Error('Not authorized');
          case 404: throw new Error('Resource not found');
          case 429: throw new Error('Too many requests');
          case 500: throw new Error('Server error');
          default: throw new Error(`HTTP error: ${response.status}`);
        }
      }

      const data = await response.json();
      addToast(data.data, 'success');
    } catch (err) {
      if (err instanceof TypeError) {
        addToast('Network error - check your connection', 'error');
      } else {
        addToast(err.message, 'error');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="demo">
      <h1>Error Handling - Demo</h1>
      <p>Click a button to simulate different server responses:</p>

      <div className="button-grid">
        <button className="btn success" onClick={() => testScenario('success')} disabled={loading}>
          200 OK (Success)
        </button>
        <button className="btn warning" onClick={() => testScenario('404')} disabled={loading}>
          404 Not Found
        </button>
        <button className="btn danger" onClick={() => testScenario('500')} disabled={loading}>
          500 Server Error
        </button>
        <button className="btn danger" onClick={() => testScenario('network')} disabled={loading}>
          Network Error
        </button>
      </div>

      {loading && <p className="status">Sending request...</p>}
    </div>
  );
}

function App() {
  return (
    <ToastProvider>
      <ErrorDemo />
    </ToastProvider>
  );
}

export default App;

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. What is an Error Boundary in React and when does it activate?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the increasing delays in the exponential backoff strategy (from shortest to longest):

  • Code editor

    Toast System

  • Click in order

    Click the elements in order of the try/catch/finally block:

  • Click in order

    Arrange the error handling syntax with async/await:

  • Horizontal ordering

    Arrange the syntax for a condition that checks the HTTP response status code:

  1. Put in orderExponential Backoff - Retry Delays
  2. QuestionError Boundary in React
  3. Coding taskPractice: Toast Notifications
  4. Click in ordertry/catch/finally Block
  5. Click in ordertry/catch Block with async/await
  6. Put in orderHTTP Status Code Check Syntax

Useful articles