Error Handling
Learn to handle both network failures and HTTP errors gracefully so your app stays reliable.
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.