better-result Adoption
Migrate existing error handling (try/catch, Promise rejections, thrown exceptions) to typed Result-based error handling with better-result.
When to Use
- Adopting better-result in existing codebase
- Converting try/catch blocks to Result types
- Replacing thrown exceptions with typed errors
- Migrating Promise-based code to Result.tryPromise
- Introducing railway-oriented programming patterns
Migration Strategy
1. Start at Boundaries
Begin migration at I/O boundaries (API calls, DB queries, file ops) and work inward. Don't attempt full-codebase migration at once.
2. Identify Error Categories
Before migrating, categorize errors in target code:
| Category | Example | Migration Target |
|---|---|---|
| Domain errors | NotFound, Validation | TaggedError + Result.err |
| Infrastructure | Network, DB connection | Result.tryPromise + TaggedError |
| Bugs/defects | null deref, type error | Let throw (becomes Panic if in Result callback) |
3. Migration Order
- Define TaggedError classes for domain errors
- Wrap throwing functions with Result.try/tryPromise
- Convert imperative error checks to Result chains
- Refactor callbacks to generator composition
Pattern Transformations
Try/Catch to Result.try
typescript1// BEFORE 2function parseConfig(json: string): Config { 3 try { 4 return JSON.parse(json); 5 } catch (e) { 6 throw new ParseError(e); 7 } 8} 9 10// AFTER 11function parseConfig(json: string): Result<Config, ParseError> { 12 return Result.try({ 13 try: () => JSON.parse(json) as Config, 14 catch: (e) => new ParseError({ cause: e, message: `Parse failed: ${e}` }), 15 }); 16}
Async/Await to Result.tryPromise
typescript1// BEFORE 2async function fetchUser(id: string): Promise<User> { 3 const res = await fetch(`/api/users/${id}`); 4 if (!res.ok) throw new ApiError(res.status); 5 return res.json(); 6} 7 8// AFTER 9async function fetchUser(id: string): Promise<Result<User, ApiError | UnhandledException>> { 10 return Result.tryPromise({ 11 try: async () => { 12 const res = await fetch(`/api/users/${id}`); 13 if (!res.ok) throw new ApiError({ status: res.status, message: `API ${res.status}` }); 14 return res.json() as Promise<User>; 15 }, 16 catch: (e) => (e instanceof ApiError ? e : new UnhandledException({ cause: e })), 17 }); 18}
Null Checks to Result
typescript1// BEFORE 2function findUser(id: string): User | null { 3 return users.find((u) => u.id === id) ?? null; 4} 5// Caller must check: if (user === null) ... 6 7// AFTER 8function findUser(id: string): Result<User, NotFoundError> { 9 const user = users.find((u) => u.id === id); 10 return user 11 ? Result.ok(user) 12 : Result.err(new NotFoundError({ id, message: `User ${id} not found` })); 13} 14// Caller: yield* findUser(id) in Result.gen, or .match()
Callback Hell to Generator
typescript1// BEFORE 2async function processOrder(orderId: string) { 3 try { 4 const order = await fetchOrder(orderId); 5 if (!order) throw new NotFoundError(orderId); 6 const validated = validateOrder(order); 7 if (!validated.ok) throw new ValidationError(validated.errors); 8 const result = await submitOrder(validated.data); 9 return result; 10 } catch (e) { 11 if (e instanceof NotFoundError) return { error: "not_found" }; 12 if (e instanceof ValidationError) return { error: "invalid" }; 13 throw e; 14 } 15} 16 17// AFTER 18async function processOrder(orderId: string): Promise<Result<OrderResult, OrderError>> { 19 return Result.gen(async function* () { 20 const order = yield* Result.await(fetchOrder(orderId)); 21 const validated = yield* validateOrder(order); 22 const result = yield* Result.await(submitOrder(validated)); 23 return Result.ok(result); 24 }); 25} 26// Error type is union of all yielded errors
Defining TaggedErrors
See references/tagged-errors.md for TaggedError patterns.
Workflow
- Check for source reference: Look for
opensrc/directory - if present, read the better-result source code for implementation details and patterns - Audit: Find try/catch, Promise.catch, thrown errors in target module
- Define errors: Create TaggedError classes for domain errors
- Wrap boundaries: Use Result.try/tryPromise at I/O points
- Chain operations: Convert if/else error checks to .andThen or Result.gen
- Update signatures: Change return types to Result<T, E>
- Update callers: Propagate Result handling up call stack
- Test: Verify error paths with .match or type narrowing
Common Pitfalls
- Over-wrapping: Don't wrap every function. Start at boundaries, propagate inward.
- Losing error info: Always include cause/context in TaggedError constructors.
- Mixing paradigms: Once a module returns Result, callers should too (or explicitly .unwrap).
- Ignoring Panic: Callbacks that throw become Panic. Fix the bug, don't catch Panic.
References
- TaggedError Patterns - Defining and matching typed errors
opensrc/directory (if present) - Full better-result source code for deeper context