Sub topic 15
Argument Validation and When Errors Are Thrown
This chapter assumes you know how map, filter, take, and drop work, and that you understand lazy evaluation: helper callbacks run only when a value is pulled with next(). You should also be comfortable with generator functions and try...catch.
Iterator helpers report problems at two different times. Some errors are thrown at once, when you call the helper method. Others are thrown later, when a value is pulled through the pipeline. Knowing which is which helps you place try...catch blocks correctly. It also helps you read stack traces that point somewhere other than where the bug was written.
Two Moments When Errors Can Happen
An iterator pipeline has a build phase and a run phase. During the build phase you call .map(...), .take(...), and so on, and each call returns a new helper object. During the run phase something pulls values: toArray, a for...of loop, a spread, or a manual next() call.
The helpers check their arguments in the build phase. Anything that depends on the data, such as a callback throwing on a particular value, can only fail in the run phase.
Eager Checks in the Build Phase
The receiver must be an object
Every helper first checks its this value. If the receiver is not an object, you get a TypeError straight away. The helper does not check that the receiver inherits from Iterator.prototype. Any object works, and the helper reads its next method when it is created.
try {
Iterator.prototype.map.call(42, (x) => x);
} catch (e) {
console.log(e instanceof TypeError); // true
}
const plain = {
i: 0,
next() {
return this.i < 2 ? { value: this.i++, done: false } : { value: undefined, done: true };
},
};
console.log(Iterator.prototype.map.call(plain, (x) => x * 10).toArray()); // [0, 10]Borrowing a method with .call like this is rare in practice. Iterator.from, covered in its own chapter, is the cleaner way to adapt such objects.
Callbacks must be callable
map, filter, and flatMap throw a TypeError at creation time if their argument is not a function. The consuming methods forEach, some, every, find, and reduce do the same check before they read any values.
const it = [1, 2, 3].values();
try {
it.map('double');
} catch (e) {
console.log(e instanceof TypeError); // true
}The pipeline never gets built, so the mistake surfaces on the line that contains it.
Limits for take and drop are converted, then checked
take(limit) and drop(limit) run the same steps on their argument:
- Convert it with
ToNumber. A BigInt or a Symbol makes this step throw aTypeError. - If the result is
NaN, throw aRangeError. - Truncate it toward zero.
InfinitystaysInfinity. - If the result is negative, throw a
RangeError.
Because the conversion goes through ToNumber, some surprising inputs are accepted. This loop shows each case:
const cases = [
['3', 3], ['2.7', 2.7], ["'2'", '2'], ['null', null], ['Infinity', Infinity],
['-0.5', -0.5], ['-1', -1], ['NaN', NaN], ['undefined', undefined], ['1n', 1n],
];
for (const [label, limit] of cases) {
try {
const out = [10, 20, 30].values().take(limit).toArray();
console.log(label, '->', JSON.stringify(out));
} catch (e) {
console.log(label, '->', e.constructor.name);
}
}
// 3 -> [10,20,30]
// 2.7 -> [10,20]
// '2' -> [10,20]
// null -> []
// Infinity -> [10,20,30]
// -0.5 -> []
// -1 -> RangeError
// NaN -> RangeError
// undefined -> RangeError
// 1n -> TypeError| Input | Converted limit | Result |
|---|---|---|
| `2.7` | `2` | Accepted, fractional part dropped |
| `'2'` | `2` | Accepted, string converted |
| `null` | `0` | Accepted, takes nothing |
| `-0.5` | `-0`, treated as `0` | Accepted, not negative after truncation |
| `-1` | `-1` | `RangeError` |
| `undefined`, `NaN`, `'abc'` | `NaN` | `RangeError` |
| `1n`, a Symbol | none | `TypeError` from conversion |
The conversion itself happens at creation time. If you pass an object, its valueOf runs before the helper is returned:
const limit = {
valueOf() {
console.log('valueOf called');
return 2;
},
};
const t = [1, 2, 3].values().take(limit);
console.log('created');
console.log(t.toArray());
// valueOf called
// created
// [1, 2]Lazy Errors in the Run Phase
A callback that throws on certain data can only fail when that data arrives. The error appears at the consumer, which may be far from the .map call that caused it. Before rethrowing, the helper closes the source iterator, so a generator's finally block runs:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('source closed');
}
}
const pipeline = source().map((n) => {
if (n === 2) throw new Error('bad value: ' + n);
return n * 10;
});
console.log('pipeline built');
try {
for (const v of pipeline) console.log(v);
} catch (e) {
console.log('caught', e.message);
}
// pipeline built
// 10
// source closed
// caught bad value: 2There is one asymmetry. If the source's own next() throws, the helper does not call return() on it. The source raised the failure, so it is treated as already finished.
Gotcha: Hand-Written Generator Helpers Validate Late
If you write your own helper as a generator function, the checks at the top of its body do not run when you call it. A generator body starts on the first next(), so the bad argument goes unnoticed until consumption:
function* myTake(iter, limit) {
if (!(limit >= 0)) throw new RangeError('limit must be >= 0');
for (const v of iter) {
if (limit-- <= 0) return;
yield v;
}
}
const bad = myTake([1, 2, 3], -1);
console.log('created without error');
try {
bad.next();
} catch (e) {
console.log('thrown on first next:', e.name);
}
// created without error
// thrown on first next: RangeErrorTo match the built-in behavior, validate in an ordinary function and then return the generator:
function myTakeEager(iter, limit) {
if (!(limit >= 0)) throw new RangeError('limit must be >= 0');
return (function* () {
let remaining = limit;
for (const v of iter) {
if (remaining-- <= 0) return;
yield v;
}
})();
}
try {
myTakeEager([1, 2, 3], -1);
} catch (e) {
console.log('thrown at creation:', e.name); // thrown at creation: RangeError
}Where to Put try...catch
- Wrap the build phase if limits or callbacks come from user input or configuration. That is where
RangeErrorandTypeErrorfrom bad arguments appear. - Wrap the consuming call (
toArray, thefor...ofloop,reduce) to catch data-dependent errors from callbacks or from the source. - If you build a pipeline in one function and consume it in another, the consumer's stack trace will show the callback. Name your callbacks so the trace stays readable.
Exercise
For each line, say whether it throws at creation, throws when consumed, or succeeds, and give the result or error type: (a) [1,2,3].values().drop('1').toArray() (b) [1,2,3].values().take(undefined) (c) [1,2,3].values().filter(null) (d) [1,2,3].values().map((x) => x.foo.bar).toArray()
Show answer
(a) Succeeds with [2, 3]; '1' converts to 1. (b) Throws a RangeError at creation, because undefined converts to NaN. (c) Throws a TypeError at creation, because null is not callable. (d) Creation succeeds; consuming throws a TypeError on the first value, because (1).foo is undefined and reading .bar from undefined fails.
Exercise
A teammate's function function* everyNth(iter, n) { if (n < 1) throw new RangeError('n'); ... } passes its unit test, expect(() => everyNth(src, 0)).toThrow(). Except the test fails. Why, and how should the function change?
Show answer
Calling a generator function only creates the generator object. The check in the body does not run until the first next(), so calling everyNth(src, 0) does not throw. Move the validation into a normal function that checks n and then returns an inner generator, or change the test to consume the result (for example everyNth(src, 0).next()) if lazy validation is intended.
Exercise
Why does [1,2,3].values().take(-0.5).toArray() return [] instead of throwing a RangeError?
Show answer
The limit is truncated toward zero before the negativity check. -0.5 becomes -0, and -0 < 0 is false, so the check passes and take uses a limit of zero.