How to Handle Errors in Fetch in JavaScript: Simple Guide
fetch in JavaScript, always check if the response is successful by testing response.ok and throw an error if not. Use try-catch blocks with async/await or .catch() on promises to catch network or parsing errors.Why This Happens
The fetch function in JavaScript does not throw an error for HTTP error statuses like 404 or 500. It only throws for network errors. This means if you try to use fetch without checking the response status, your code might think the request succeeded even when the server returned an error.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log('Data:', data)) .catch(error => console.error('Error:', error));
The Fix
Check the response.ok property to see if the HTTP status is in the success range (200-299). If not, throw an error to be caught later. Use try-catch with async/await for clearer code and better error handling.
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log('Data:', data); } catch (error) { console.error('Fetch error:', error.message); } } fetchData();
Prevention
Always check response.ok before processing the response data. Use try-catch blocks with async/await or .catch() on promises to handle both HTTP errors and network failures. Consider using helper functions to centralize error handling and keep your code clean.
Enable linting rules that warn about unhandled promises and missing error handling to catch mistakes early.
Related Errors
Common related errors include:
- NetworkError when fetch fails: Happens when there is no internet or the server is unreachable.
- SyntaxError when parsing JSON: Occurs if the response is not valid JSON but you call
response.json(). - Unhandled promise rejections: Forgetting to add
.catch()ortry-catchleads to uncaught errors.