Course contentsShow
← JavaScript
Lesson 2043 of 2,72342. Iteration Protocols Deep DiveFree lesson

Error Handling in Async Generators

Learn how to throw errors from async generators and handle them in consuming code with try/catch.

Error Handling in Async Generators

What you'll learn: How to throw errors from async generators and catch them safely in your consuming code.

Async generators can fail just like any async operation. When an error occurs inside an async generator (whether from a rejected promise or a thrown exception), you need a way to handle it gracefully in the code that's consuming the generator.

Throwing Errors from Async Generators

When an error is thrown inside an async generator, it propagates to the consuming code at the point where next() was awaited (or during for-await-of iteration):

async function* riskyGenerator() {
  yield 1;
  yield 2;
  throw new Error('Something went wrong!');
  yield 3; // Never reached
}

Catching Errors with Try-Catch

Wrap your for-await-of loop or manual next() calls in a try-catch block:

async function consume() {
  try {
    for await (const value of riskyGenerator()) {
      console.log(value); // Logs 1, then 2
    }
  } catch (error) {
    console.log('Caught:', error.message); // 'Something went wrong!'
  }
}

Manual Iteration Error Handling

When calling next() manually, the promise it returns will reject if the generator throws:

async function manualConsume() {
  const gen = riskyGenerator();
  try {
    console.log(await gen.next()); // {value: 1, done: false}
    console.log(await gen.next()); // {value: 2, done: false}
    console.log(await gen.next()); // Promise rejects here
  } catch (error) {
    console.log('Error caught:', error.message);
  }
}

Think of error handling in async generators like error handling in async functions—the error becomes a rejected promise that you catch where you're awaiting results.

Key Takeaway: Errors thrown inside async generators propagate to consuming code and can be caught with try-catch blocks around for-await-of loops or awaited next() calls.