Web APIs & FetchAdvanced
1Question 1 of 1
javascriptHow does the Fetch API handle HTTP requests and error status codes?
Explanation & Concept
The `fetch()` API makes asynchronous network requests returning a Promise that resolves to a `Response` object.
Crucial Gotcha: `fetch()` **does not reject on HTTP error status codes** (like 404 or 500). It only rejects on network failures or blocked requests (CORS). You must manually check `response.ok` (which is true for 200–299 status codes).
Code Example
javascript
async function fetchPost(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: "GET",
headers: { "Accept": "application/json" }
});
// Check HTTP status code
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Fetch request failed:", error.message);
}
}
fetchPost(1);How It Works & Key Takeaways
Checking `response.ok` ensures application logic correctly catches 4xx and 5xx API errors rather than attempting to parse erroneous response bodies.
Mock Test · 1 Questions · Optional
Ready for Error Handling & Custom Errors?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions