Sub topic 2
Handling Errors Correctly: Why fetch Resolves on 404
This chapter assumes you know Promises, async/await, try/catch, and basic HTTP status codes and headers.
Network Errors Versus HTTP Error Statuses
The Promise from fetch() rejects only when no response arrives at all. A DNS failure, a dropped connection, or a blocked CORS request will cause a rejection. A 404 or 500 is still a valid HTTP response, so the Promise resolves. To treat those statuses as failures, check response.ok, which is true only for statuses 200–299.
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
return response.json();
}
getUser(1)
.then((user) => console.log(user))
.catch((err) => console.error('Request failed:', err.message));Configuring Requests: Methods, Headers, and Bodies
You can pass a second argument to fetch(): an options object. The main options are method, which defaults to 'GET', plus headers and body. PUT and DELETE requests use the same options as POST and change only the method value.
Sending JSON and Form Data
To send JSON, serialize the object with JSON.stringify and set Content-Type so the server knows how to parse the body.
async function createPost(post) {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
createPost({ title: 'Hello', body: 'First post' });Working with the Headers Interface
The Headers interface lets you build headers step by step. append() adds a value and set() replaces any existing one. get() and has() read headers back, and header names are case-insensitive.
async function getMe() {
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.set('Authorization', 'Bearer TOKEN');
const response = await fetch('https://api.example.com/me', { headers });
console.log(response.headers.get('content-type'));
console.log(headers.has('authorization')); // true
}
getMe();Exercise
A request to a missing endpoint returns 404, but your .catch() handler never runs and response.json() throws a parse error instead. Why, and how do you fix it?
Show answer
fetch resolves for any HTTP response, including 404, so .catch() is not reached. The code then tries to parse an HTML or empty error page as JSON. Check response.ok before parsing and throw an error when it is false.
Exercise
Why should you leave out the Content-Type header when the body is a FormData object?
Show answer
The browser generates the multipart/form-data header, including the boundary string. If you set the header by hand, the boundary is missing and the server cannot parse the body.