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
okonly when requested. - Values passed to
.next(value)are forwarded to the source. - A normal generator
returnis preserved asok(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
finallyblocks run. - Without filters, the error type is
unknown. Constructor arrays infer the selected error union.
Component props
Prop
Type
Default
Name
generatorOrFactoryDescription
The synchronous generator instance or lazy factory to wrap.
Type
Generator<Y, R, N> | (() => Generator<Y, R, N>)Default
-
Name
errorsToCatchDescription
Optional constructor list. Non-matching errors are re-thrown.
Type
ErrorClass[]Default
-
Component props
Prop
Type
Default
Name
generatorOrFactoryDescription
The asynchronous generator instance or lazy factory to wrap.
Type
AsyncGenerator<Y, R, N> | (() => AsyncGenerator<Y, R, N>)Default
-
Name
errorsToCatchDescription
Optional constructor list. Non-matching rejections are re-thrown.
Type
ErrorClass[]Default
-