JavaScript

Lesson 06

Async error handling

Handle failed requests and unsuccessful response statuses before parsing data.

Good Code

load-profile.js
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." };
  }
}

Bad Code

load-profile.js
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 };
}

Review Notes

What to review

Good Code

The good version separates transport failures from unsuccessful HTTP responses and only parses JSON after the response is acceptable.

Bad Code

The bad version is concise, but it assumes every request succeeds and every response body can be parsed as JSON.

Takeaways

  • Check both network failures and response status before trusting fetched data.