0
0
JavascriptDebug / FixBeginner · 4 min read

How to Handle Errors in Fetch in JavaScript: Simple Guide

To handle errors in 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.

javascript
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error));
Output
Data: { error: 'Not Found' } // or unexpected data without error indication
🔧

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.

javascript
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();
Output
Fetch error: HTTP error! status: 404
🛡️

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() or try-catch leads to uncaught errors.

Key Takeaways

Always check response.ok to detect HTTP errors in fetch.
Use try-catch with async/await or .catch() on promises to handle errors.
Throw errors manually when response.ok is false to catch HTTP errors.
Handle both network errors and JSON parsing errors gracefully.
Use linting tools to ensure all fetch calls handle errors properly.