Programming paths / JavaScript

JavaScript learning path

Write robust JavaScript for browsers and servers using asynchronous control flow, modules, and defensive data handling.

Starter lesson

Handle failed HTTP responses

A network request can fail at the transport layer, and an HTTP response can still indicate an error. Check both cases before using response data.

async function loadProfile(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }
  return response.json();
}

loadProfile('/api/profile')
  .then(profile => console.log(profile.name))
  .catch(error => console.error(error.message));

What to expect

On success, the profile name is logged. Network and HTTP failures are sent to the catch handler.

Key idea: Treat network data as untrusted input and make failure behavior part of the function contract.

← Browse all programming paths