Keep malformed success responses out
A response with status 200 can still be unusable. Validate its parsed body before giving it to the rest of the app. A decoder should either return normalized records or fail clearly; callers should not have to guess whether half the fields are usable.
Yesterday's loadCount stopped after response.json(). Here it gains the last stage: the same kind of shape check you wrote on Day 1, now sitting after the HTTP steps. That gives one adapter four separate ways to fail: the request rejects (no response), the status is not ok, the body is not JSON, or the JSON has the wrong shape. Unknown extra properties may be ignored if the contract says so; missing required fields may not.
Store the result only after every required check succeeds. Assigning parsed raw data to state and then checking it can briefly render bad data, or leave corruption behind after failure. Prepare a valid next value first, then commit the change.
Catch boundaries need to distinguish programming defects from expected user-facing failure. You can show a message at a UI boundary and still keep diagnostics available during development. Do not silently substitute zero for a malformed count: that changes "unknown" into a plausible but false business value.
Predict and trace
refresh calls the full adapter and, on any failure, keeps the count it already had and records why. Predict the four lines. The starting count is 7.
async function main() {
function decodeCount(body) {
if (
body === null ||
typeof body !== "object" ||
Array.isArray(body) ||
!Number.isInteger(body.count) ||
body.count < 0
) {
throw new Error("Invalid count");
}
return body.count;
}
async function loadCount(request) {
const response = await request("/count"); // rejects: network failure
if (!response.ok) {
throw new Error(`HTTP ${response.status}`); // a response, but not success
}
const body = await response.json(); // rejects: body is not JSON
return decodeCount(body); // throws: JSON with the wrong shape
}
async function refresh(state, request) {
try {
const count = await loadCount(request);
return { count, error: null };
} catch (error) {
return { count: state.count, error: error.message };
}
}
const requests = {
offline: async () => {
throw new Error("Network unavailable");
},
down: async () => ({ ok: false, status: 503, json: async () => ({}) }),
malformed: async () => ({ ok: true, status: 200, json: async () => ({ count: "3" }) }),
valid: async () => ({ ok: true, status: 200, json: async () => ({ count: 3 }) })
};
let state = { count: 7, error: null };
for (const [name, request] of Object.entries(requests)) {
state = await refresh(state, request);
console.log(`${name}: count ${state.count}, error ${state.error}`);
}
}
main();Check your prediction
offline: count 7, error Network unavailable
down: count 7, error HTTP 503
malformed: count 7, error Invalid count
valid: count 3, error nullEach failure comes from a different stage (the comments in loadCount mark them), yet refresh handles all of them in one place: the adapter throws, and the caller decides what the screen keeps. The count changes only on the last line, after every stage succeeded. Writing state.count = ... before decoding, or replacing it with 0 in the catch, would put a value on screen that the server never sent.
Try the rule on new inputs
Add a notJson request whose json is async () => JSON.parse("oops"). Which stage fails, and what is error.name? Then put valid first in the list and confirm that every later failure keeps 3, not 7.
Build it yourself
A new endpoint, end to end
/books answers in a different shape from the count example: a successful body is an envelope, { items: [{ title }, ...] }, and when there is nothing to send the server answers 204 No Content with no body at all. Write all three layers:
decodeTitles(body)returns the trimmed titles and throws for any other shape, including a bare array, or for one missing or blank title;loadTitles(request)requests"/books", treats 204 as an empty list without reading the body, throwsHTTP <status>for other failures, and decodes the JSON;refreshTitles(state, request)returns{ titles, error: null }on success, and on any failure keepsstate.titleswitherrorset to"invalid JSON"for a parse failure, otherwise the error's message.
The test sends one fake response per stage, in order, and should print:
valid: Notes, The Web (error: none)
broken JSON: Notes, The Web (error: invalid JSON)
bare list: Notes, The Web (error: Expected { items: [...] })
blank title: Notes, The Web (error: Invalid book)
missing: Notes, The Web (error: HTTP 404)
no content: (no titles) (error: none)async function main() {
function decodeTitles(body) {
// Accept { items: [{ title }, ...] }; return the trimmed titles.
// Throw for any other shape, or for a missing or blank title.
return [];
}
async function loadTitles(request) {
// Request "/books"; handle 204, a non-ok status, and the JSON body.
return [];
}
async function refreshTitles(state, request) {
// Return { titles, error }. Keep state.titles when anything fails.
return state;
}
// ---- test: fake responses, one per stage ----
const respond = (status, json) => async () => ({ ok: status >= 200 && status < 300, status, json });
const requests = {
valid: respond(200, async () => ({ items: [{ title: " Notes " }, { title: "The Web" }] })),
"broken JSON": respond(200, async () => JSON.parse("<html>")),
"bare list": respond(200, async () => [{ title: "Notes" }]),
"blank title": respond(200, async () => ({ items: [{ title: "Notes" }, { title: " " }] })),
missing: respond(404, async () => ({})),
"no content": respond(204, async () => JSON.parse(""))
};
let state = { titles: [], error: null };
for (const [name, request] of Object.entries(requests)) {
state = await refreshTitles(state, request);
console.log(`${name}: ${state.titles.join(", ") || "(no titles)"} (error: ${state.error ?? "none"})`);
}
}
main();Hint 1: the idea
Each layer has one job, as in loadCount above: decodeTitles knows the body's shape, loadTitles knows HTTP, and refreshTitles decides what the screen keeps. A 204 is a successful response, but calling json() on it would fail because there is no body to parse, so loadTitles must check for it before reading the body.
Hint 2: a first step
Start with decodeTitles and test it on its own with a few hand-written bodies before wiring anything. Then write loadTitles without the 204 check and refreshTitles with its try/catch, and run: every line except the last should match, and no content reports invalid JSON. That wrong line tells you where the 204 check belongs.
Show one solution
async function main() {
function decodeTitles(body) {
if (body === null || typeof body !== "object" || !Array.isArray(body.items)) {
throw new Error("Expected { items: [...] }");
}
return body.items.map(book => {
if (
book === null ||
typeof book !== "object" ||
typeof book.title !== "string" ||
book.title.trim() === ""
) {
throw new Error("Invalid book");
}
return book.title.trim();
});
}
async function loadTitles(request) {
const response = await request("/books");
if (response.status === 204) {
return []; // success with no body: do not call json()
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return decodeTitles(await response.json());
}
async function refreshTitles(state, request) {
try {
return { titles: await loadTitles(request), error: null };
} catch (error) {
const reason = error instanceof SyntaxError ? "invalid JSON" : error.message;
return { titles: state.titles, error: reason };
}
}
// ---- test: fake responses, one per stage ----
const respond = (status, json) => async () => ({ ok: status >= 200 && status < 300, status, json });
const requests = {
valid: respond(200, async () => ({ items: [{ title: " Notes " }, { title: "The Web" }] })),
"broken JSON": respond(200, async () => JSON.parse("<html>")),
"bare list": respond(200, async () => [{ title: "Notes" }]),
"blank title": respond(200, async () => ({ items: [{ title: "Notes" }, { title: " " }] })),
missing: respond(404, async () => ({})),
"no content": respond(204, async () => JSON.parse(""))
};
let state = { titles: [], error: null };
for (const [name, request] of Object.entries(requests)) {
state = await refreshTitles(state, request);
console.log(`${name}: ${state.titles.join(", ") || "(no titles)"} (error: ${state.error ?? "none"})`);
}
}
main();valid: Notes, The Web (error: none)
broken JSON: Notes, The Web (error: invalid JSON)
bare list: Notes, The Web (error: Expected { items: [...] })
blank title: Notes, The Web (error: Invalid book)
missing: Notes, The Web (error: HTTP 404)
no content: (no titles) (error: none)The three layers fail in different ways, and refreshTitles handles all of them in one catch. decodeTitles rejects the bare array because the contract is the envelope, which stops a list from an older endpoint from being accepted by accident. loadTitles checks status === 204 before ok, since 204 counts as ok, and returns [] without calling json(), whose parse of an empty body is exactly the SyntaxError that would otherwise appear. JSON.parse failures are SyntaxErrors, so instanceof SyntaxError names the parsing stage without depending on the browser's wording. Every failure keeps the last good titles, while the 204 is a real success and replaces them with an empty list: "the server has nothing" is not the same as "the request failed".
Explain before moving on
Where should the decoder sit relative to rendering? Why is returning an empty default different from rejecting malformed data?
Completion is saved in this browser only. It does not measure mastery.