Overview
functionError Handling

catchKind

Recovers one discriminated domain error variant by its `kind` field.

Signature

tsSignature
export function catchKind<
I,
O,
E extends TaggedError,
C extends object,
K extends E["kind"],
O2,
E2 = never,
>(
source: Behavior<I, O, E, C>,
kind: K,
handler: (
error: Extract<E, { kind: K }>,
input: I,
context: TaskContext<C>,
) => Awaitable<Result<O2, E2>>,
): Behavior<I, O | O2, Exclude<E, { kind: K }> | E2, C>;

Imports

tsImport
import { catchKind } from "@/lib/flow/catch-kind";
import { catchKind } from "@/lib/flow";

Type Parameters

I

Input type.

O

Source output type.

E

Tagged source domain error union.

C

Custom context type.

K

Error kind handled by this recovery step.

O2

Handler output type.

E2

Handler domain error type.

Parameters

source
Behavior<I, O, E, C>

Behavior whose domain error union should be narrowed.

kind
K

Specific `kind` value to recover.

handler
( error: Extract<E, { kind: K }>, input: I, context: TaskContext<C>, ) => Awaitable<Result<O2, E2>>

Callback invoked for matching domain errors.

Returns

A behavior with the handled error variant removed unless the handler returns a new error.

Return type
Behavior<I, O | O2, Exclude<E, { kind: K }> | E2, C>

Details

Matching errors are passed to the handler. Non-matching domain errors remain typed, and runtime

errors bypass the handler.

Examples

tsExample
const withDefault = catchKind(loadSettings, "missing", (_error, _input, context) =>
context.ok({ theme: "system" }),
);
Awaitable

Represents a value that may be returned directly or through a Promise.

type
Behavior

Executable Flow workflow unit.

type
input

Creates an identity behavior for starting typed pipelines.

function
Result

Explicit success-or-failure outcome used throughout Flow.

type

Source

tsflow/catch-kind.ts:34-72
export function catchKind<
I,
O,
E extends TaggedError,
C extends object,
K extends E["kind"],
O2,
E2 = never,
>(
source: Behavior<I, O, E, C>,
kind: K,
handler: (
error: Extract<E, { kind: K }>,
input: I,
context: TaskContext<C>,
) => Awaitable<Result<O2, E2>>,
): Behavior<I, O | O2, Exclude<E, { kind: K }> | E2, C> {
return async (input, context) => {
const result = await runBehavior(source, input, context);
if (result.ok) {
return result;
}
if (isRuntimeError(result.error)) {
return err(result.error);
}
const error = result.error as E & TaggedError;
if (error.kind !== kind) {
return err(error as Exclude<E, { kind: K }>);
}
return task((_input: I, taskContext: TaskContext<C>) =>
handler(error as Extract<E, { kind: K }>, input, taskContext),
)(input, context);
};
}