Good Code
The good version separates transport failures from unsuccessful HTTP responses and only parses JSON after the response is acceptable.
Lesson 06
Handle failed requests and unsuccessful response statuses before parsing data.
async function loadProfile(userId) {
// Check HTTP status before parsing and catch transport failures.
try {
const response = await fetch("/api/users/" + userId);
if (!response.ok) {
return { ok: false, error: "Profile request failed." };
}
const profile = await response.json();
return { ok: true, profile };
} catch {
return { ok: false, error: "Network error while loading profile." };
}
}async function loadProfile(userId) {
// Happy-path parsing turns failures into unhandled exceptions.
const response = await fetch("/api/users/" + userId);
const profile = await response.json();
return { ok: true, profile };
}The good version separates transport failures from unsuccessful HTTP responses and only parses JSON after the response is acceptable.
The bad version is concise, but it assumes every request succeeds and every response body can be parsed as JSON.