throwIf
Throws when a predicate holds; otherwise returns the value unchanged.
Lecture
throwIf(predicate, toError, value) is a guard clause you can
drop mid-expression: if predicate(value) is true, it throws
toError(value); otherwise it hands value back
unchanged. That makes it convenient inside a map callback,
where you want to validate every element as it streams through the
pipeline and fail loudly the moment one is invalid.
It's essentially when where the
"then" branch always throws instead of returning a value — so wrap any
call site in try/catch to observe or recover
from the failure.
Demo 1 · Basics
Demo 2 · Validating a pipeline
Each age is validated as it's mapped; the first violation aborts the
whole toList() call:
Try it yourself
Exercise: use throwIf to guard against zero stock while
summing this inventory.
throwError — a standalone throwing function, no condition ·
when — substitute a value instead of throwing ·
cases — dispatch across multiple predicates ·
add — used above as the reducer