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

fxFoldRaise

Runs a block in a fresh Raise<E> scope and folds whatever happens — a value, a raised error, or a thrown exception — into one result type.

B fxFoldRaise<E, A, B>(A Function(Raise<E> r) block, {required B Function(E error) onRaise, required B Function(A value) onValue, B Function(Object thrown, StackTrace stackTrace)? onThrow}) Future<B> fxFoldRaiseAsync<E, A, B>(FutureOr<A> Function(Raise<E> r) block, {required FutureOr<B> Function(E error) onRaise, required FutureOr<B> Function(A value) onValue, FutureOr<B> Function(Object thrown, StackTrace stackTrace)? onThrow})

Lecture

fxEither turns a raise block into an Either; fxNullable turns one into a T?. Both are one call to fxFoldRaise, the single primitive every builder derives from — the port of Arrow's fold. It runs block with a new scope r and dispatches on how the block ended:

Reach for it when neither an Either nor a T? is the shape you want at the boundary — a status string, an HTTP response, a record, a sealed type of your own — and you would otherwise build an Either only to switch on it on the next line. It is also how you write a builder of your own: fxEither is fxFoldRaise with an onRaise that builds a Left and an onValue that builds a Right, and nothing else. onThrow is the three-clause form that fxEitherCatching and r.recover pass through; the raise signal itself is never handed to it.

fxFoldRaiseAsync is the async twin: the block and every handler may await, and the same rule as fxEitherAsync applies — raise only within the awaited chain. The scope is closed when the fold returns, so a lazy pipeline that would raise later must be materialized inside the block. Named fxFoldRaise because fxFold already exists.

Demo 1 · Three outcomes, one result type

Demo 2 · A builder of your own, nesting & async

Try it yourself

Exercise: skip the intermediate Either and fold the scope straight into the message.

Related: fxEither & the Raise scope — the builder built on it · fxNullable — the info-free builder, also one fold · Either — fold on a value you already have · typed errors — full guide