#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
HTTP

Handling HTTP Errors

Handling HTTP errors in React means planning for every way a request can fail, a dropped connection, a server returning 404 or 500, a body that is not valid JSON, and showing the user something useful instead of a blank screen or a frozen spinner. Error handling sits right next to loading state in any component that talks to an API.

Two very different kinds of failure

The fetch function treats failures in a way that surprises many developers:

  • Network failures, such as no internet, a wrong domain or a CORS block, make the promise reject. These land in catch.
  • HTTP error statuses, such as 400, 401, 404 or 500, still resolve the promise. As far as fetch is concerned, the server answered. You must check response.ok (true for 200 to 299) or response.status yourself.

If you only write a catch, a 500 error will slip past it and your code will try to use the error page as data.

A component that handles both

import { useState, useEffect } from 'react';

export default function MovieList() {
  const [movies, setMovies] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  async function loadMovies() {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/movies');

      if (!response.ok) {
        let message = `Server error (${response.status})`;
        try {
          const body = await response.json();
          if (body.message) message = body.message;
        } catch {
          // body was not JSON; keep the generic message
        }
        throw new Error(message);
      }

      setMovies(await response.json());
    } catch (err) {
      setError(err.message || 'Something went wrong');
    } finally {
      setIsLoading(false);
    }
  }

  useEffect(() => {
    loadMovies();
  }, []);

  if (isLoading) return <p>Loading movies...</p>;

  if (error) {
    return (
      <div role="alert">
        <p>{error}</p>
        <button onClick={loadMovies}>Try again</button>
      </div>
    );
  }

  if (movies.length === 0) return <p>No movies found.</p>;

  return <ul>{movies.map((m) => <li key={m.id}>{m.title}</li>)}</ul>;
}

The component throws its own Error for bad statuses so both failure types reach one catch. It tries to read a message from the server but falls back if the body is HTML or empty. finally always clears the loading flag.

Choosing what to tell the user

StatusUsual causeHelpful response
400 / 422Invalid inputShow the field errors next to the form.
401Not logged in or token expiredSend the user to log in again.
403No permissionExplain the action is not allowed.
404Item missingSay it was not found; offer a way back.
500+Server problemApologise briefly and offer a retry.

Keep technical detail such as stack traces out of the interface. Log it with console.error during development or send it to a monitoring tool in production.

Where error handling commonly goes wrong

Besides skipping the response.ok check, the frequent slip is setting isLoading to false only on success. When the request fails, the spinner keeps spinning forever. Putting it in finally fixes that. Another is forgetting to reset error before a retry, so the old message stays on screen even after the second attempt succeeds.

Also remember that React error boundaries do not catch errors thrown inside event handlers or asynchronous code such as fetch. Request errors must be caught and stored in state, as above.

Quick recap

Check response.ok because fetch only rejects on network failure, throw your own error for bad statuses, read the server's message when available, clear loading in finally, and render an error state with a retry button. Later you can move this logic into a custom hook so every component handles errors the same way.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course