Tezeract logo

Handling Error in React | 7 Best Practices YOU Should Know

Error Handling in ReactJS

Content

import React, { useState, useEffect } from 'react';

// ErrorBoundary functional component to catch errors
const ErrorBoundary = ({ children }) => {
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const handleErrors = (error, errorInfo) => {
      // You can log the error to a service like Sentry or display a user-friendly message
      console.error('Error caught by ErrorBoundary:', error, errorInfo);
      setHasError(true);
    };

    // Attach the error handler to the global error event
    window.addEventListener('error', handleErrors);

    return () => {
      // Remove the error handler when the component unmounts
      window.removeEventListener('error', handleErrors);
    };
  }, []);

  if (hasError) {
    return <div>Something went wrong. Please try again later.</div>;
  }

  return children;
};

// Your functional component wrapped with the ErrorBoundary
const MyComponent = () => {
  const [count, setCount] = useState(0);

  // Simulate an error by dividing by zero
  if (count === 5) {
    throw new Error('This is a simulated error!');
  }

  return (
    <ErrorBoundary>
      <div>
        <h1>Counter: {count}</h1>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    </ErrorBoundary>
  );
};

export default MyComponent;
  • ErrorBoundary is a functional component that uses the useEffect hook to attach and remove a global error handler to catch errors.
  • If an error occurs in the child components (e.g., when the counter reaches 5), it will be caught by the global error handler, and an error message will be displayed instead of crashing the entire app.
import React, { useState } from 'react';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    try {
      // Simulate an API call that may throw an error
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        throw new Error('Failed to fetch data');
      }

      const result = await response.json();
      setData(result);
    } catch (error) {
      // Handle the error and update the state
      setError(error.message);
    }
  };

  return (
    <div>
      <h1>Data Fetching Example</h1>
      <button onClick={fetchData}>Fetch Data</button>

      {error && <div style={{ color: 'red' }}>{error}</div>}

      {data && (
        <div>
          <h2>Received Data:</h2>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default MyComponent;
  • fetchData is an asynchronous function that simulates fetching data from an API using the fetch function.
  • The try block contains the code that may throw an error, such as checking the response status and parsing JSON.
  • If any error occurs during the try block, the catch block is executed, and the error is caught and handled. In this case, the error message is stored in the error state variable.
  • The component renders a button to trigger the data fetching, and it displays the error message or the fetched data based on the state.
import React, { useState } from 'react';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const fetchData = () => {
    fetch('https://api.example.com/data')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        return response.json();
      })
      .then((result) => {
        // Process the data
        setData(result);
      })
      .catch((error) => {
        // Handle errors in the promise chain
        setError(error.message);
      });
  };

  return (
    <div>
      <h1>Data Fetching Example</h1>
      <button onClick={fetchData}>Fetch Data</button>

      {error && <div style={{ color: 'red' }}>{error}</div>}

      {data && (
        <div>
          <h2>Received Data:</h2>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default MyComponent;
  • The fetchData function uses the fetch API to make an asynchronous call to ‘https://api.example.com/data’.
  • The .then method is used to handle the successful response and process the JSON data.
  • The .catch method is used to handle any errors that may occur during the asynchronous operation. If the response status is not okay, an error is thrown and caught in the catch block. The error message is then stored in the error state variable.
  • The component renders a button to trigger the data fetching, and it displays the error message or the fetched data based on the state.
Daniyal Habib

Daniyal Habib

MERN Stack Developer

Share

Suggested Articles