API Error Handling in React
CIIT Training Institute | React API Integration
1. Introduction to API Error Handling
When React applications communicate with APIs, different errors can occur. The server may return an error response, the internet connection may fail, or the response may contain invalid data.
API error handling helps us detect these problems and display meaningful messages instead of leaving users confused.
response.ok.
2. Types of API Errors
| Error Type | Description | Example |
|---|---|---|
| Network Error | The request cannot reach the server. | Internet connection lost. |
| 404 Not Found | The requested resource does not exist. | Invalid API endpoint. |
| 401 Unauthorized | Authentication is missing or invalid. | Invalid access token. |
| 500 Server Error | The server encountered a problem. | Internal server failure. |
| Invalid JSON | The response cannot be parsed as JSON. | Malformed response data. |
3. Using response.ok
The response.ok property is true when the HTTP status
code indicates success, usually in the 200–299 range. If it is
false, we can throw an error and handle it in the catch block.
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(
`HTTP Error: ${response.status}`
);
}
const data = await response.json();
console.log(data);
response.ok explicitly.
4. Using try, catch and finally
JavaScript provides three useful blocks for handling errors during API requests.
- try: Contains the code that may fail.
- catch: Handles errors thrown by the request or processing logic.
- finally: Runs whether the request succeeds or fails.
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(
`Request failed: ${response.status}`
);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("API Error:", error.message);
} finally {
console.log("Request completed.");
}
5. Complete React Example
In this example, we fetch users from an API and display the data. If the request fails, React displays an error message. The loading indicator is cleared after the request finishes.
import { useEffect, useState } from "react";
function APIErrorHandling() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function fetchUsers() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(
`Unable to load users. Status: ${response.status}`
);
}
const data = await response.json();
if (!Array.isArray(data)) {
throw new Error(
"Invalid data received from the server."
);
}
setUsers(data);
} catch (err) {
setError(
err instanceof Error
? err.message
: "Something went wrong."
);
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return (
<div>
<p role="alert">Error: {error}</p>
</div>
);
}
return (
<div>
<h2>User List</h2>
{users.length === 0 ? (
<p>No users found.</p>
) : (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
)}
</div>
);
}
export default APIErrorHandling;
6. How Error Handling Works
7. Best Practices
- Always check
response.okfor Fetch requests. - Display clear, user-friendly error messages.
- Use
finallyto reset loading state. - Validate API data before using it.
- Do not expose passwords, access tokens or sensitive server details in error messages.
- Log technical details appropriately during development.
- For retry functionality, use a deliberate retry strategy rather than retrying every error indefinitely.
8. Practice Tasks
- Fetch posts from JSONPlaceholder and display them.
- Use an invalid endpoint and display a suitable error message.
- Display a loading message while fetching data.
- Handle HTTP error responses using
response.ok. - Validate the response data before rendering it.
- Add a Retry button that allows users to try the request again.
Summary
API error handling makes React applications more reliable and user-friendly. By checking HTTP responses, using try-catch-finally, validating returned data and displaying meaningful messages, we can manage common network and server problems effectively.