import { IterableX } from '../iterablex.js'; import { returnIterator } from '../../util/returniterator.js'; import { OperatorFunction } from '../../interfaces.js'; /** @ignore */ export class CatchWithIterable extends IterableX { private _source: Iterable; private _handler: (error: any) => Iterable; constructor(source: Iterable, handler: (error: any) => Iterable) { super(); this._source = source; this._handler = handler; } *[Symbol.iterator]() { let err: Iterable | undefined; let hasError = false; const it = this._source[Symbol.iterator](); while (1) { let done: boolean | undefined; let value: TSource; try { ({ done, value } = it.next()); if (done) { returnIterator(it); break; } } catch (e) { err = this._handler(e); hasError = true; returnIterator(it); break; } yield value; } if (hasError) { for (const item of err!) { yield item; } } } } /** * Continues an async-iterable sequence that is terminated by an exception with the * async-iterable sequence produced by the handler. * * @template TSource The type of the elements in the source sequence. * @template TResult The type of elements from the handler function. * @param {(error: any) => Iterable} handler Error handler function, producing another async-iterable sequence. * @returns {(OperatorFunction)} An operator which continues an async-iterable sequence that is terminated by * an exception with the specified handler. */ export function catchError( handler: (error: any) => Iterable ): OperatorFunction { return function catchWithOperatorFunction( source: Iterable ): IterableX { return new CatchWithIterable(source, handler); }; }