Skip to main content
This guide will walk you through the core features of better-result by building a user profile fetcher that handles errors gracefully.

What We’ll Build

We’ll create a function that:
  • Fetches user data from an API
  • Parses and validates the response
  • Handles multiple error types (network, parsing, validation)
  • Uses generator composition for clean control flow
  • Provides type-safe error handling with pattern matching
1

Create Ok and Err Results

Let’s start with the basics — creating success and error Results:
Results use a discriminated union with status: "ok" | "error" for type narrowing.
2

Wrap Throwing Functions

Most JavaScript APIs throw exceptions. Wrap them with Result.try to convert exceptions into type-safe Results:
The error type is UnhandledException by default. We’ll create custom error types next.
3

Define Tagged Errors

Create discriminated error types for exhaustive pattern matching:
Now we can use custom error handlers in Result.try:
4

Compose with Result.gen

The real power of better-result comes from generator composition. Use yield* to unwrap Results and automatically short-circuit on errors:
user-profile.ts
yield* unwraps Ok values and short-circuits on Err. Use Result.await() to wrap Promise<Result> in async generators.
5

Handle Errors with Pattern Matching

Now use the function and handle all possible errors:
main.ts
matchError ensures all error cases are handled. TypeScript will error if you miss any error types!
Alternatively, use Result.match() for inline pattern matching:
6

Transform Results

Use .map() and .andThen() to transform Results:

Complete Example

Here’s the full working example:

What You’ve Learned

You now know how to:
  • ✅ Create Ok and Err results
  • ✅ Wrap throwing functions with Result.try and Result.tryPromise
  • ✅ Define custom error types with TaggedError
  • ✅ Compose operations with Result.gen and yield*
  • ✅ Handle errors exhaustively with pattern matching
  • ✅ Transform Results with .map() and .andThen()

Next Steps

Result Type Deep Dive

Learn about all Result methods and combinators

Error Handling Patterns

Master TaggedError and error composition patterns

Generator Composition

Understand how Result.gen works under the hood

API Reference

Explore the complete API documentation