SmartCodingTips

๐Ÿšจ Error Handling in Async Code

When working with Promises and async/await, handling errors properly is crucial to prevent crashes and unexpected behavior.

โŒ Without Error Handling

async function getData() {
  const res = await fetch('https://invalid-url');
  const data = await res.json(); // If fetch fails, this will not run
  console.log(data);
}

getData();

This will throw a runtime error if the fetch fails.

โœ… Using try...catch with async/await

async function getData() {
  try {
    const res = await fetch('https://invalid-url');
    if (!res.ok) {
      throw new Error('โŒ Network response was not ok');
    }
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('๐Ÿ”ฅ Error:', error.message);
  } finally {
    console.log("โœ… Finished trying to fetch data");
  }
}

getData();

๐Ÿงช Common Scenarios

  • Network errors (invalid URLs, server down)
  • JSON parsing issues
  • Timeouts or unresponsive APIs
  • Manually thrown errors inside async blocks

๐Ÿ’ก Tips

  • Always wrap async logic inside try...catch
  • Use finally for cleanup actions
  • Check res.ok before using res.json()
  • Use error boundaries in UI frameworks like React
๐Ÿ’ก Reminder: Unhandled Promise rejections will crash Node.js apps and be silenced in browsers. Always handle errors!