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
fetchis concerned, the server answered. You must checkresponse.ok(true for 200 to 299) orresponse.statusyourself.
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
| Status | Usual cause | Helpful response |
|---|---|---|
| 400 / 422 | Invalid input | Show the field errors next to the form. |
| 401 | Not logged in or token expired | Send the user to log in again. |
| 403 | No permission | Explain the action is not allowed. |
| 404 | Item missing | Say it was not found; offer a way back. |
| 500+ | Server problem | Apologise 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.