Handling Fetch
Responses
Learn how to work with JSON data from APIs and gracefully handle HTTP errors using JavaScript's Fetch API.
What is the Fetch API?
The Fetch API is a modern, built-in JavaScript interface for making HTTP requests to servers: loading data, submitting forms, or communicating with APIs. It returns a Promise that resolves to a Response object.
The Response Object
When fetch() resolves, it gives you a Response object. This object contains metadata about the server's reply, plus methods to read the actual data.
The Fetch Lifecycle
The Core Pattern
This is the foundational pattern for every fetch call. Memorize this structure: fetch, check, parse, catch.
.ok vs .status: Key Distinction
| response.ok | response.status | |
|---|---|---|
| Type | Boolean | Number |
| 200 response | true | 200 |
| 404 response | false | 404 |
| 500 response | false | 500 |
| Best for | Quick pass/fail check | Specific error branching |
Why Fetch Doesn't Reject on HTTP Errors
This is the most surprising behavior of fetch(): a 404 or 500 response does not cause the Promise to reject. The Promise only rejects on network failures: no internet, DNS errors, or CORS blocks.
How to Handle a Fetch Response
Example 1: Fetching User Data
Example 2: Status Branching
Example 3: The .then() Chain Approach
You can also handle fetch responses without async/await by chaining .then() and .catch(). The logic is identical: check, parse, handle errors.
Remember: .json() is Async
Network Error vs HTTP Error
What if the Response Isn't JSON?
Calling .json() on a non-JSON response (like HTML or plain text) will throw a SyntaxError. The Response object offers other parsing methods for different content types.
Common Mistakes
Summary Cheat Sheet
| Scenario | What Happens | How to Handle |
|---|---|---|
| 200 OK | Promise resolves, .ok is true | Parse with .json() |
| 404 Not Found | Promise resolves, .ok is false | Check .ok, throw or branch |
| 500 Server Error | Promise resolves, .ok is false | Check .ok, show error message |
| No Internet | Promise rejects (TypeError) | catch block handles it |
| Invalid JSON | .json() throws SyntaxError | catch block or use .text() |
Question 1 of 5
What does fetch() return when you call it?
Question 2 of 5
If a server returns a 404 Not Found status, what does the fetch Promise do?
Question 3 of 5
What is wrong with this code?
Question 4 of 5
Which of the following scenarios will cause the fetch Promise to reject?
Question 5 of 5
What does response.ok evaluate to when the HTTP status code is 201 Created?