Async Error Handling Patterns

This note is for patterns that handle errors in asynchronous JavaScript.

try…catch With async/await

async function loadData(){
  try {
    const response = await fetch("/api/data");
 
    if(!response.ok){
      throw new Error("Request failed");
    }
 
    const data = await response.json();
    console.log(data);
  }
  catch(error){
    console.error("Could not load data:", error);
  }
}

Pattern

  1. Put risky async code inside try.
  2. Check response.ok manually.
  3. Throw an error when the response is not valid.
  4. Handle the error in catch.

Why This Matters

fetch() only rejects on network failure. A 404 or 500 response still needs to be checked with response.ok.