Generators

Handle lazy synchronous and asynchronous streams with Result.

Catcher preserves generator laziness while turning each yielded value into a Result. A selected failure is yielded once as err, then the wrapper completes.

Use catchGenerator with a Generator instance or a factory.

generator.ts
import { catchGenerator } from '@catcherjs/core';

class RowError extends Error {}

function* readRows() {
yield { id: 1 };
throw new RowError('Invalid row');
}

for (const result of catchGenerator(readRows, [RowError, TypeError])) {
if (result.isErr()) {
  console.error(result.error.message);
  break;
}

console.log(result.data.id);
}

Use catchAsyncGenerator with for await...of for streams, pagination, queues, and other asynchronous sources.

async-generator.ts
import { catchAsyncGenerator } from '@catcherjs/core';

async function* streamPages() {
yield await fetchPage(1);
yield await fetchPage(2);
}

for await (const result of catchAsyncGenerator(streamPages())) {
if (result.isErr()) {
  console.error(result.error);
  break;
}

console.log(result.data);
}

  • Values remain lazy and are wrapped in ok only when requested.
  • Values passed to .next(value) are forwarded to the source.
  • A normal generator return is preserved as ok(value) for manual iterator consumers.
  • A caught failure is yielded once as err; non-matching filtered errors are re-thrown.
  • Breaking iteration closes the source generator so its finally blocks run.
  • Without filters, the error type is unknown. Constructor arrays infer the selected error union.

Component props

Prop
Type
Default

Component props

Prop
Type
Default