response.ok, try/catch & retrying
Loading and error states
Lesson 14 of 20 · 13 min · Module 4: Talk to a server
Networks are slow and sometimes fail. A good page tells people what is happening while they wait, explains when something went wrong, and offers a way to try again.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Check response.ok for HTTP errors
- Handle failures with try/catch
- Show loading, error and retry states
The idea
fetch only rejects when the request cannot be made at all, for example when the connection is down. A server error such as 500 still resolves, so check response.ok and throw an error yourself when it is false. One try/catch then handles both kinds of failure.
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
} catch (error) {
console.error('Loading failed:', error.message);
}
01Two kinds of failure
A network failure (no connection, blocked request) makes fetch reject. An HTTP error (404, 500) is a perfectly delivered response that happens to say something went wrong. Checking response.ok turns the second kind into the first.
const response = await fetch('/missing');
console.log(response.ok, response.status);false 40402Every state is visible
Loading, success, empty, and error are all states your page can be in. Designing a message for each one prevents blank screens that leave people wondering whether anything is happening.
03Retry is cheap kindness
Many errors are temporary. A Try again button that simply calls the same function again turns a dead end into a small delay.
Your turn
loadCourses(): first set #status to Loading courses… and hide #retry. Fetch /api/courses; if response.ok is false, throw an error. On success, render one <li> per course with its title and set the status to 3 courses loaded. On any error, set the status to Could not load courses. Please try again. and show #retry. Clicking #retry calls loadCourses() again.What the checks look for
- A loading message shows while waiting
- The courses appear when they arrive
- A server error shows a message and a retry button
- A network failure is handled too
- Try again loads the courses
Take this with you
Check response.ok, catch every failure, and always show what is happening.
Go a little further
Disable the retry button while a request is in progress, and add a small delay before showing the loading message to avoid flicker on fast connections.