Result & Errors
Massaman treats expected failure as data. A fallible operation returns a Result<T> so its caller can see and handle both outcomes without relying on an exception path.
The error parameter preserves specific Error types while defaulting to Error for existing Result<T> call sites. Thrown and rejected values still exist at unsafe boundaries; attempt, attemptAsync, and err normalize non-Error values before returning an Err.
Why it matters
Exceptions hide failure outside a function's return type. A Result makes failure visible, keeps it local to the data flow, and gives TypeScript a discriminated union to narrow.
This creates a clear boundary:
- unsafe code may throw or reject
attemptorattemptAsynccatches that outcome once- application code handles
OkandErras ordinary values
Core tools
AbortError and TimeoutError provide recognizable error types for cancellation and time limits. They can be carried by an Err like any other Error.
When to use it
Use Result when failure is expected and the caller can respond:
- parsing untrusted input
- reading files or configuration
- calling a network or storage boundary
- enforcing a domain rule that can reject a value
Construct ok and err in functions that model fallibility directly. Use attempt and attemptAsync around APIs that communicate failure by throwing or rejecting.
Typed errors
Use defineError for reusable domain errors without subclasses. err preserves their specific types, and literal names let pattern matching narrow each failure's data.
Inference is the default: omit the generics when the definition already describes the contract. An inline function definition infers its arguments and literal name. An object definition creates a zero-argument constructor. ReturnType<typeof notFound> extracts the instance type when you do not need to declare it upfront.
For one-off errors, call createError directly:
Both constructors create native Error instances with fresh stacks and optional causes. Custom data is shallowly copied; its fields are readonly in TypeScript, not frozen at runtime. Return errors through err for expected failures. Throw them only at a deliberate exception boundary.
Existing Error intersections, interfaces, and subclasses still work. Passing a plain object directly to err still normalizes it into Err<Error>; use createError or defineError to preserve typed custom fields.
Continue and recover
Results remain plain objects. Use standalone functions to avoid repeating success/error checks; there are no chain methods or wrappers.
andThencalls the next operation only on success. On failure, it returns the originalErrunchanged. The next operation may fail with a different error type; both types are preserved as a union.orElsecalls recovery only on failure. On success, it returns the originalOkunchanged. Recovery can fail too; its error type replaces the original error type. Returnerr(error)from recovery if you want to retain an original error.unwrapOrreturns a plain success value or fallback without throwing onErr. Successfulnull,undefined, and other falsy values are not replaced. The fallback is evaluated before the call, even on success; use literals or already-computed values, not expensive or fallible work.
Callbacks must return synchronous Results. Unexpected callback exceptions propagate rather than being silently converted to failures. Use attempt at throwing boundaries. Await an attemptAsync result before passing it to these helpers; use explicit guards when the next step itself must await more work.
Combine batch outcomes
Choose whether the batch requires every item to succeed or allows partial success:
collectResults mirrors Rust's collection into Result<Vec<T>, E>. partitionResults mirrors the Rust itertools crate's partition_result: it unwraps both groups and retains every error, making it useful for imports and batch validation. Neither helper mutates the input, clones payloads, or renormalizes errors. Both preserve order within their output arrays and infer unions for distinct value and error types. Tuple positions and record inputs are not supported.
Collection is not execution: in collectResults(rows.map(parseRow)), every row has already been parsed by map. The first-error policy only determines the returned outcome; it cannot undo that work or skip later parsing. Exceptions during input creation still need attempt. For asynchronous batches, await the Results first, for example partitionResults(await Promise.all(tasks)); these helpers do not manage concurrency or cancel running work.
Complete example
The unsafe operation is isolated in parseConfig. Everything after it handles typed data, and every result variant is covered.
When not to use it
Do not wrap every branch in a Result.
- Use a domain union such as
User | NotFoundwhen both variants are normal outcomes. - Let programmer errors fail loudly; they are bugs, not recoverable domain values.
- Use
unwraponly where crashing is the intended policy, such as required boot configuration.
Result describes expected failure. It is not a replacement for every union or every exception.
Related reference
attemptandattemptAsyncok,err,isOk, andisErrunwrapandtoErrorandThen,orElse, andunwrapOrcollectResultsandpartitionResultscreateError,defineError, andErrorWithAbortErrorandTimeoutError- Pattern Matching