Error Handling

Learn to handle both network failures and HTTP errors gracefully so your app stays reliable.

Step 1 of 6

Two Kinds of Errors

When making HTTP requests, two fundamentally different things can go wrong, and they require different handling:

1. Network errors — The request never reached the server at all. The user's WiFi dropped, the server is down, or there's a DNS failure. In this case, fetch() rejects its Promise, and your catch block will fire. The user literally could not connect.

2. HTTP errors — The request reached the server, and the server responded, but the response indicates a problem: 404 (not found), 403 (forbidden), 500 (server error), etc. Here's the tricky part: fetch() considers this a successful exchange because the network worked fine. The Promise resolves normally. You have to check response.ok yourself to detect these.

This distinction is critical. If you only use try/catch, you'll catch network errors but miss HTTP errors entirely. If you only check response.ok, you'll catch HTTP errors but crash on network failures. You need both for robust error handling.

Think of it this way: Imagine sending a letter. A network error is like the letter getting lost in the mail — it never arrived, and you never got any reply. An HTTP error is like the letter arriving, but the recipient writing back 'Wrong address' or 'I can't help you.' In both cases something went wrong, but the nature of the failure is completely different.