|
| 1 | +--- |
| 2 | +name: better-result-adopt |
| 3 | +description: Adopt better-result in an existing TypeScript codebase. Use when replacing try/catch, Promise rejection handling, null sentinels, or thrown domain exceptions with typed Result workflows. |
| 4 | +references: |
| 5 | + - references/tagged-errors.md |
| 6 | +--- |
| 7 | + |
| 8 | +# better-result Adopt |
| 9 | + |
| 10 | +Adopt `better-result` incrementally in existing codebases without rewriting everything at once. |
| 11 | + |
| 12 | +## When to Use |
| 13 | + |
| 14 | +Use this skill when the user wants to: |
| 15 | + |
| 16 | +- migrate from try/catch to `Result.try` or `Result.tryPromise` |
| 17 | +- replace nullable return values with typed `Result<T, E>` |
| 18 | +- define domain-specific `TaggedError` types |
| 19 | +- refactor nested error handling into `andThen` chains or `Result.gen` |
| 20 | +- standardize error handling across a service or module |
| 21 | + |
| 22 | +## Reading Order |
| 23 | + |
| 24 | +| Task | Files to Read | |
| 25 | +| -------------------------------------- | ----------------------------- | |
| 26 | +| Adopt better-result in a module | This file | |
| 27 | +| Define or review error types | `references/tagged-errors.md` | |
| 28 | +| Inspect library implementation details | `opensrc/` if present | |
| 29 | + |
| 30 | +## Prerequisites |
| 31 | + |
| 32 | +Before editing code: |
| 33 | + |
| 34 | +1. Confirm `better-result` is already installed in the target project. |
| 35 | +2. Check for an `opensrc/` directory. If present, read the package source there for current patterns. |
| 36 | +3. Identify the migration scope first: one file, one module, or one boundary layer. |
| 37 | + |
| 38 | +## Migration Strategy |
| 39 | + |
| 40 | +### 1. Start at boundaries |
| 41 | + |
| 42 | +Begin with I/O boundaries and exception-heavy code: |
| 43 | + |
| 44 | +- HTTP clients |
| 45 | +- database access |
| 46 | +- file system operations |
| 47 | +- parsing and validation |
| 48 | +- framework adapters |
| 49 | + |
| 50 | +Do not convert the whole codebase at once. |
| 51 | + |
| 52 | +### 2. Classify existing failures |
| 53 | + |
| 54 | +| Category | Examples | Target shape | |
| 55 | +| --------------------- | --------------------------- | -------------------------------------------------------------- | |
| 56 | +| Domain errors | not found, validation, auth | `TaggedError` + `Result.err` | |
| 57 | +| Infrastructure errors | network, DB, file I/O | `Result.tryPromise` + mapped error | |
| 58 | +| Programmer defects | bad assumptions, null deref | leave throwing; defects become `Panic` inside Result callbacks | |
| 59 | + |
| 60 | +### 3. Migrate in this order |
| 61 | + |
| 62 | +1. Define error types. |
| 63 | +2. Wrap throwing boundaries with `Result.try` / `Result.tryPromise`. |
| 64 | +3. Replace null or boolean sentinel returns with `Result`. |
| 65 | +4. Refactor call sites to propagate `Result` values. |
| 66 | +5. Collapse nested branching into `andThen`, `mapError`, or `Result.gen`. |
| 67 | + |
| 68 | +## Core Transformations |
| 69 | + |
| 70 | +### Try/catch → `Result.try` |
| 71 | + |
| 72 | +```ts |
| 73 | +function parseConfig(json: string): Result<Config, ParseError> { |
| 74 | + return Result.try({ |
| 75 | + try: () => JSON.parse(json) as Config, |
| 76 | + catch: (cause) => new ParseError({ cause, message: `Parse failed: ${cause}` }), |
| 77 | + }); |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +### Async throws → `Result.tryPromise` |
| 82 | + |
| 83 | +```ts |
| 84 | +async function fetchUser(id: string): Promise<Result<User, ApiError | UnhandledException>> { |
| 85 | + return Result.tryPromise({ |
| 86 | + try: async () => { |
| 87 | + const res = await fetch(`/api/users/${id}`); |
| 88 | + if (!res.ok) throw new ApiError({ status: res.status, message: `API ${res.status}` }); |
| 89 | + return res.json() as Promise<User>; |
| 90 | + }, |
| 91 | + catch: (cause) => (cause instanceof ApiError ? cause : new UnhandledException({ cause })), |
| 92 | + }); |
| 93 | +} |
| 94 | +``` |
| 95 | + |
| 96 | +### Null sentinel → `Result` |
| 97 | + |
| 98 | +```ts |
| 99 | +function findUser(id: string): Result<User, NotFoundError> { |
| 100 | + const user = users.find((candidate) => candidate.id === id); |
| 101 | + return user |
| 102 | + ? Result.ok(user) |
| 103 | + : Result.err(new NotFoundError({ id, message: `User ${id} not found` })); |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +### Nested flow → `Result.gen` |
| 108 | + |
| 109 | +```ts |
| 110 | +async function processOrder(orderId: string): Promise<Result<OrderResult, OrderError>> { |
| 111 | + return Result.gen(async function* () { |
| 112 | + const order = yield* Result.await(fetchOrder(orderId)); |
| 113 | + const validated = yield* validateOrder(order); |
| 114 | + const result = yield* Result.await(submitOrder(validated)); |
| 115 | + return Result.ok(result); |
| 116 | + }); |
| 117 | +} |
| 118 | +``` |
| 119 | + |
| 120 | +## Execution Workflow |
| 121 | + |
| 122 | +1. Audit the target module for `try`, `catch`, `.catch(...)`, `throw`, `null`, `undefined`, and status-flag error handling. |
| 123 | +2. Define or update `TaggedError` classes before changing control flow. |
| 124 | +3. Convert boundary functions first and change their signatures to `Result<T, E>` or `Promise<Result<T, E>>`. |
| 125 | +4. Update immediate callers so they handle or propagate the new `Result`. |
| 126 | +5. Where multiple Result-returning steps compose, use `Result.gen` or `andThen`. |
| 127 | +6. Preserve error context by keeping `cause`, IDs, messages, and other structured fields. |
| 128 | +7. Run tests and add coverage for both success and error paths. |
| 129 | + |
| 130 | +## Completion Criteria |
| 131 | + |
| 132 | +A migration is complete when: |
| 133 | + |
| 134 | +- target functions no longer rely on try/catch for expected domain failures |
| 135 | +- nullable or sentinel error returns are replaced with explicit `Result` values |
| 136 | +- domain failures use typed `TaggedError` classes |
| 137 | +- callers either propagate `Result` or explicitly unwrap/match it |
| 138 | +- tests cover at least one success path and one representative error path |
| 139 | + |
| 140 | +## Common Pitfalls |
| 141 | + |
| 142 | +- Over-wrapping everything instead of starting at boundaries |
| 143 | +- Losing original failure context when mapping errors |
| 144 | +- Mixing `throw`-based and `Result`-based APIs deep in the same flow |
| 145 | +- Catching `Panic` instead of fixing the underlying defect |
| 146 | + |
| 147 | +## In This Reference |
| 148 | + |
| 149 | +| File | Purpose | |
| 150 | +| ----------------------------- | --------------------------------------------------------- | |
| 151 | +| `references/tagged-errors.md` | TaggedError patterns, matching, type guards, and examples | |
| 152 | + |
| 153 | +If `opensrc/` exists, treat it as the source of truth for implementation details and current API behavior. |
0 commit comments