SyntaxStudy
Sign Up
JavaScript Error Handling with async/await
JavaScript Intermediate 8 min read

Error Handling with async/await

Error Handling with async/await

When using async/await, errors from rejected promises are thrown as exceptions inside the async function. This means you can handle them with standard try/catch/finally blocks — the same syntax used for synchronous errors — making error handling consistent across your codebase.

try/catch

Wrap your awaited calls in a try block. If any awaited promise rejects, execution jumps to the catch block with the rejection reason as the caught error.

finally

The finally block runs regardless of success or failure, making it ideal for cleanup tasks like hiding a loading spinner or closing database connections.

Error Propagation

If you do not catch an error in an async function, the returned promise is rejected with that error, propagating it to the caller. This allows you to handle errors at the appropriate level of abstraction.

Example
async function riskyFetch(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('HTTP error: ' + response.status);
  }
  return response.json();
}
async function loadData() {
  let loading = true;
  try {
    const data = await riskyFetch('https://api.example.com/data');
    console.log('Success:', data);
  } catch (err) {
    console.error('Failed:', err.message);
  } finally {
    loading = false;
    console.log('Loading:', loading);
  }
}
loadData();
async function withDefault(url, fallback) {
  try {
    return await riskyFetch(url);
  } catch {
    return fallback;
  }
}
Pro Tip

Check response.ok after every fetch() call — a fetch only rejects on network failure, not on HTTP error status codes like 404 or 500. You must throw manually for those cases.