01 / 21

Handling Fetch
Responses

Learn how to work with JSON data from APIs and gracefully handle HTTP errors using JavaScript's Fetch API.

JavaScript

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.

const response = await fetch('https://api.example.com/data');

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.

response.ok
Boolean: true if status is 200-299
response.status
HTTP status code: 200, 404, 500, etc.
response.json()
Parses body as JSON, returns a Promise

The Fetch Lifecycle

fetch(url) Promise (pending...) Response object Check response.ok throw Error HTTP error handling false .json() parse body true JSON Data

The Core Pattern

This is the foundational pattern for every fetch call. Memorize this structure: fetch, check, parse, catch.

async function getData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Fetch failed:', error); } }

.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.

Promise Resolves
200 OK, 201 Created, 404 Not Found, 500 Server Error: all of these resolve the Promise
Promise Rejects
Network offline, DNS failure, CORS blocked: these are the only cases that reject

How to Handle a Fetch Response

1
Call fetch(url) with your endpoint URL. This returns a Promise.
2
Await the Response object. The Promise resolves once headers arrive.
3
Check response.ok. If false, throw an error with the status code.
4
Parse with .json(). This is also async: await the returned Promise.
5
Wrap in try/catch to handle both network errors and your thrown HTTP errors.

Example 1: Fetching User Data

async function getUser(id) { try { const response = await fetch( `https://api.example.com/users/${id}` ); if (!response.ok) { throw new Error(`User not found: ${response.status}`); } const user = await response.json(); console.log(user.name); } catch (error) { console.error(error.message); } } getUser(42);

Example 2: Status Branching

async function fetchProduct(id) { const response = await fetch(`/api/products/${id}`); if (response.status === 404) { return { error: 'Product not found' }; } if (response.status === 401) { return { error: 'Please log in first' }; } if (!response.ok) { return { error: 'Something went wrong' }; } return await response.json(); }

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.

fetch('https://api.example.com/posts') .then(response => { if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('Failed:', error); });

Remember: .json() is Async

Response (headers ready) .json() Promise (reading body...) await JS Object (your data!)
// WRONG: data is a Promise, not an object const data = response.json(); // CORRECT: await the Promise const data = await response.json();

Network Error vs HTTP Error

fetch(url) no internet Network Error Promise REJECTS Caught by .catch() TypeError thrown server replies HTTP Error (404, 500) Promise RESOLVES NOT caught by .catch() Must check .ok manually 200 OK: Success 200

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.

.json()
Parses as JSON: objects, arrays, strings, numbers
.text()
Returns raw text: HTML pages, plain text, CSV
.blob()
Returns binary data: images, PDFs, files

Common Mistakes

✕ No .ok Check
Assuming fetch() throws on 404/500. It doesn't: you must check response.ok yourself.
✕ Forgetting await on .json()
Writing const data = response.json() gives you a Promise, not actual data. Always await it.
✕ No try/catch
Skipping error handling entirely. Network failures will crash your app with an unhandled rejection.

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?

const response = await fetch('/api/data'); const data = response.json(); console.log(data.name);

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?