Error Handling with Try/Catch in Async Code

1. Welcome and Icebreaker:

  • If you could catch and handle any mistake in your life before it happens, what would it be?

2. Outline the Session:

  • We’ll learn how to handle errors in asynchronous code using try/catch with async/await.
  • Learning Outcomes: Understand how to catch and handle errors in async functions.
  • Let’s handle errors gracefully!

3. Concept Explanation:

  • Error Handling in Async Code: Use try/catch blocks inside async functions to catch errors from awaited Promises.
  • If a Promise rejects, control jumps to the catch block.
  • You can also use .catch() on Promises, but try/catch is more readable with async/await.
  • Syntax:
    async function run() {
      try {
        const result = await fetchData();
        // ...
      } catch (error) {
        // handle error
      }
    }
    

4. Live Coding Demonstration:

function fetchData(shouldFail = false): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldFail) reject("Failed to load data!");
      else resolve("Data loaded!");
    }, 1000);
  });
}

async function showData() {
  try {
    const data = await fetchData(true);
    console.log(data);
  } catch (error) {
    console.error("Caught error:", error);
  }
}

showData();

5. Tasks:

  • Short Exercise:
    1. Write an async function that throws an error and catch it with try/catch.
    2. Modify a function to handle both success and failure cases.
    3. Try using try/catch inside a loop with async operations.