Network and offline behaviour
Turn a vague failure report into a reproduction, isolate the cause, form and falsify hypotheses, instrument the code, fix async and state bugs, lock the fix behind a regression test and review changes for real trade-offs.
What you will be able to do
#- Tell a timeout, an abort, a client error, a server error and an offline state apart.
- Make a request cancellable and a retry safe.
Overview
#A network call is not a function call. It can be slow, fail, return partial data, or finish after the user has moved on. Treating those outcomes as one generic error hides the real cause.
Classify the failure before you handle it. A timeout means no response arrived in time. An abort means the caller cancelled the request. A 4xx means the request was wrong and retrying will not help. A 5xx or a dropped connection may be worth a retry. Offline means the browser knows there is no network, which is a state, not an exception.
Make every request cancellable so a stale response cannot overwrite a newer one and so navigation does not leave work running.
async function load(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error('request failed with status ' + res.status);
return res.json();
}
A timeout is an abort with a reason. Combine an AbortController with a timer, and clear the timer when the request settles so it does not fire later.
Retries must be safe. Retry only idempotent requests, or attach an idempotency key so the server can recognise a repeat. Use exponential backoff with jitter so many clients do not retry in lockstep, and cap the number of attempts.
async function withRetry(fn, attempts) {
let lastError;
for (let i = 0; i < attempts; i += 1) {
try {
return await fn();
} catch (error) {
lastError = error;
const delay = Math.min(1000 * 2 ** i, 8000) + Math.random() * 100;
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw lastError;
}
Every request needs four visible states: loading, success, empty and error, plus an offline variant. A screen that only renders success will show stale or blank content when the network fails. Optimistic updates need a rollback path so a failed write restores the previous value instead of leaving the UI ahead of the server.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Debug
This fetch has no timeout and no cancellation, so a slow request can hang forever and a stale response can land after the user leaves. Add an AbortController with a timeout, and distinguish an abort from a real failure.
starter.javascriptasync function load(url) { const res = await fetch(url); return res.json(); }Reveal the reference answer
reference.javascriptasync function load(url, timeoutMs) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url, { signal: controller.signal }); if (!res.ok) throw new Error('request failed with status ' + res.status); return await res.json(); } catch (error) { if (error.name === 'AbortError') throw new Error('request timed out after ' + timeoutMs + 'ms'); throw error; } finally { clearTimeout(timer); } }Authored expected output: load rejects with a timeout message when the request exceeds timeoutMs, rejects with the status message on a bad response, and clears the timer when the request settles.
The original has no way to stop a slow request. Passing a signal lets the caller or a timer cancel it, and checking the error name separates an intentional abort from a genuine failure. Clearing the timer in finally prevents a late abort of a completed request.
Exercise 2Explain
Give a review rubric for how a screen handles the network, including which failures may be retried and which must not be.
Reveal the reference answer
reference.textCheck that the screen renders loading, success, empty, error and offline states rather than only success. Check that each request is cancellable so a stale response cannot overwrite a newer one and so navigation stops the work. Classify failures before handling them: a 4xx means the request was wrong and must not be retried, while a 5xx, a timeout or a dropped connection may be retried if the request is idempotent or carries an idempotency key. Retries use exponential backoff with jitter and a capped attempt count. Optimistic updates must have a rollback path that restores the previous value when the write fails.Authored expected output: A rubric covering the visible states, cancellation, failure classification, safe retry policy and rollback for optimistic updates.
Most network bugs are missing states or unsafe retries. Naming the states and the retry rules up front turns an ad hoc handler into a reviewable contract.
Common misconceptions
#- Every failed request should be retried.
- A request that has not returned is the same as a request that failed.
Follow-up practice
#- debugging-review-16-data-and-validation
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.