-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathonError.ts
44 lines (42 loc) · 1.12 KB
/
onError.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* @author electricessence / https://github.com/electricessence/
* @license MIT
*/
import ArgumentNullException from '@tsdotnet/exceptions/dist/ArgumentNullException';
import {IterableFilter} from '../IterableTransform';
/**
* An iterable filter that invokes the provided handler if there was an error while iterating.
* Any error while iterating assumes no more results and the iteration will be complete after the error.
* The handler can decide if it wants to rethrow the error or not.
* @param {(ex: any, index: number) => void} handler
* @return {IterableFilter<T>}
*/
export default function onError<T> (
handler: (ex: any, index: number) => void
): IterableFilter<T> {
if(!handler) throw new ArgumentNullException('action');
return function(sequence: Iterable<T>): Iterable<T> {
return {
* [Symbol.iterator] (): Iterator<T>
{
const iterator = sequence[Symbol.iterator]();
let i = 0;
while(true)
{
try
{
const next = iterator.next();
if(next.done) break;
yield next.value;
}
catch(ex)
{
handler(ex, i);
break;
}
i++;
}
}
};
};
}