Error Handling and Retries
0 558
๐จ Why Error Handling Matters in React
Whether you're fetching data from an API or interacting with third-party services, errors are inevitable. Good error handling improves UX, avoids crashes, and gives users clear feedback. ๐งฏ๐ง
๐งช Common Error Scenarios
- โ Network request fails (timeout, no internet)
- ๐ Unauthorized access (401)
- ๐ Resource not found (404)
- ๐ฅ Server error (500+)
๐ฆ Basic Error Handling with Fetch
useEffect(() => {
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
return response.json();
})
.then(data => setData(data))
.catch(error => {
setError(error.message);
});
}, []);
๐ Showing Fallback UI
Let users know something went wrong:
{error ? <p className="text-red-500">Failed to load data: {error}</p> : null}
๐ Adding Retry Logic Manually
Retrying failed requests a few times before giving up improves robustness:
const fetchWithRetry = async (url, retries = 3, delay = 1000) => {
try {
const response = await fetch(url);
if (!response.ok) throw new Error("Request failed");
return await response.json();
} catch (err) {
if (retries > 0) {
await new Promise(res => setTimeout(res, delay));
return fetchWithRetry(url, retries - 1, delay);
} else {
throw err;
}
}
};
๐ Usage in useEffect
useEffect(() => {
fetchWithRetry("https://api.example.com/data")
.then(data => setData(data))
.catch(err => setError(err.message));
}, []);
โ๏ธ Using Axios with Retry Support
If you use axios, integrate retry logic with the axios-retry package.
npm install axios axios-retry
import axios from 'axios';
import axiosRetry from 'axios-retry';
axiosRetry(axios, { retries: 3, retryDelay: () => 1000 });
axios.get("https://api.example.com/data")
.then(res => setData(res.data))
.catch(err => setError(err.message));
๐ Graceful Degradation
Even if all retries fail, make sure your app handles it without crashing:
- ๐ง Show a helpful error message
- ๐ Give user an option to retry manually
- ๐ Log errors to analytics tools (e.g., Sentry)
๐ฌ Custom Retry Button
<button onClick={refetchData} className="bg-blue-500 text-white p-2 rounded">
Retry
</button>
๐ง Retry Best Practices
- ๐ Retry only for retryable errors (like 5xx, not 401 or 404)
- โฑ Add a delay between retries to avoid hammering servers
- ๐ฏ Limit number of retries (3โ5 max)
- ๐ฆ Use exponential backoff for better performance
๐ Summary
- โ Always handle errors in network calls
- โ Provide a user-friendly fallback or retry option
- โ Use retry logic for flaky or transient issues
- โ
Integrate tools like
axios-retryfor better DX
๐ Final Thoughts
Robust error handling and smart retries make your React apps more stable, professional, and user-friendly. Don't treat API errors as edge cases โ expect them, and design for them. ๐ง ๐ฅ
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments