← All tips

Tip & trick / JavaScript / API integration

fetch HTTP errors: check response.ok before parsing JSON

Check the HTTP status before parsing JSON so a server error reaches your error handler.

The server returns a JSON error with status 500. Your request reaches .then(), and the screen tries to render that error object as a successful response. Adding another catch won't fix the missing status check.

fetch resolves when it receives an HTTP response, including 404 and 500. Network failures can reject the promise. Treat those as separate failure paths. MDN documents this behavior.

Check the status before reading the body

Use this helper for endpoints that return JSON on success:

js
async function fetchJson(url, options = {}) {
  const response = await fetch(url, options);

  if (!response.ok) {
    const error = new Error(`Request failed: HTTP ${response.status}`);
    error.status = response.status;
    throw error;
  }

  return response.json();
}

async function loadProfile() {
  try {
    const profile = await fetchJson('/api/profile');
    console.log(profile);
  } catch (error) {
    console.error('Could not load profile:', error.message);
  }
}

loadProfile();

The relative URL assumes a browser app with an /api/profile endpoint. Use your server's absolute URL in a native app. On a 500 response, the helper throws before parsing the body; loadProfile handles the failure. Invalid JSON also reaches the error handler.

Give empty responses their own path

A successful 204 No Content response has nothing to parse. For a delete endpoint, check response.ok and return without calling response.json(). For an endpoint that sometimes returns JSON and sometimes 204, explicitly handle response.status === 204 before parsing.

Avoid logging entire response bodies: they may include account details or tokens. Keep the status available for your UI's retry or sign-in behavior.

Documentation checked October 3, 2026. The example uses standard Fetch APIs; it does not require a new dependency.

End of note

← Back to tips

Search articles and tips

Search in