Course contentsShow
← Web Development
Lesson 836 of 2,98215. Browser NetworkingFree lesson

Error Handling: Network vs HTTP Errors

Learn to properly catch network failures, handle HTTP error status codes, and implement retry logic.

Error Handling: Network vs HTTP Errors

You'll learn how to distinguish between network failures and HTTP error statuses, and handle each appropriately.

When working with the Fetch API, not all errors are created equal. Understanding the difference between network errors and HTTP errors is crucial for building robust applications.

The Two Types of Errors

Network Errors

These occur when the request can't reach the server at all: no internet connection, DNS lookup failure, server unreachable, or request timeout. With fetch(), these cause the Promise to reject, triggering your .catch() block.

Analogy: Like trying to call someone but getting "no signal" – the call never connects.

HTTP Errors

These happen when the server responds but with an error status code (like 404 Not Found or 500 Internal Server Error). Here's the catch: fetch() considers these successful requests because communication happened. The Promise resolves normally, even for 404 or 500 status codes!

Proper Error Handling Pattern

fetch('https://api.example.com/data')
  .then(response => {
    // Check if HTTP status indicates success
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    // Catches both network errors AND our thrown HTTP errors
    console.error('Request failed:', error.message);
  });

Always check response.ok (true for status 200-299) or response.status explicitly. Network errors automatically land in .catch(), but you must manually throw for HTTP errors.

Key Takeaway: Network errors reject the Promise; HTTP errors don't – you must check response.ok and throw manually to handle both types consistently in your catch block.