JavaScript Fetch Errors
fetch rejects only when the network itself fails. An HTTP error still resolves, so the code must check the response.
A successful response
A data URL fetch resolves with ok set to true. The status is 200, which means success.
(async () => {
const response = await fetch("data:application/json,%7B%22name%22%3A%22Ana%22%7D");
console.log(response.ok);
console.log(response.status);
})();A 404 response
A Response built with a status of 404 has ok set to false. fetch would resolve with a response like this one.
const response = new Response("Not found", { status: 404 });
console.log(response.ok);
console.log(response.status);Checking ok before reading
The code reads the body only when ok is true. When ok is false, it prints the status instead.
const response = new Response("Not found", { status: 404 });
if (response.ok) {
console.log("Read the body");
} else {
console.log("Status: " + response.status);
}Example
(async () => {
const response = await fetch("data:application/json,%7B%22name%22%3A%22Ana%22%7D");
if (response.ok) {
const data = await response.json();
console.log(data.name);
} else {
console.log("Request failed");
}
})();Key points
- ok: a property of a response that is true when the status is a success
- status: a number that names the result of a request, like 200 or 404
- A 404 status means the resource was not found.
- fetch resolves with a response even when the status is an error.
- Check response.ok before reading the body.
- A real network failure rejects the fetch promise, so catch it.
In this example, fetch returns a response with ok set to true. The code reads the body only when ok is true. The else branch stays ready for an error status.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does fetch do when the server answers with a 404 status?