本页尚未翻译,因此以英文显示。 参与翻译

fxThrowIf

Throws when a predicate holds; otherwise returns the value unchanged.

T fxThrowIf<T>(bool Function(T) predicate, Object Function(T) toError, T value)

Lecture

fxThrowIf(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 fxWhen 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 fxThrowIf to guard against zero stock while summing this inventory.

Related: fxThrowError — a standalone throwing function, no condition · fxWhen — substitute a value instead of throwing · fxCases — dispatch across multiple predicates · fxAdd — used above as the reducer