better-result-adopt

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.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "better-result-adopt" with this command: npx skills add dmmulroy/better-result/dmmulroy-better-result-better-result-adopt

better-result Adopt

Adopt better-result incrementally in existing codebases without rewriting everything at once.

When to Use

Use this skill when the user wants to:

  • migrate from try/catch to Result.try or Result.tryPromise
  • replace nullable return values with typed Result<T, E>
  • define domain-specific TaggedError types
  • refactor nested error handling into andThen chains or Result.gen
  • standardize error handling across a service or module

Reading Order

TaskFiles to Read
Adopt better-result in a moduleThis file
Define or review error typesreferences/tagged-errors.md
Inspect library implementation detailsopensrc/ if present

Prerequisites

Before editing code:

  1. Confirm better-result is already installed in the target project.
  2. Check for an opensrc/ directory. If present, read the package source there for current patterns.
  3. Identify the migration scope first: one file, one module, or one boundary layer.

Migration Strategy

1. Start at boundaries

Begin with I/O boundaries and exception-heavy code:

  • HTTP clients
  • database access
  • file system operations
  • parsing and validation
  • framework adapters

Do not convert the whole codebase at once.

2. Classify existing failures

CategoryExamplesTarget shape
Domain errorsnot found, validation, authTaggedError + Result.err
Infrastructure errorsnetwork, DB, file I/OResult.tryPromise + mapped error
Programmer defectsbad assumptions, null derefleave throwing; defects become Panic inside Result callbacks

3. Migrate in this order

  1. Define error types.
  2. Wrap throwing boundaries with Result.try / Result.tryPromise.
  3. Replace null or boolean sentinel returns with Result.
  4. Refactor call sites to propagate Result values.
  5. Collapse nested branching into andThen, mapError, or Result.gen.

Core Transformations

Try/catch → Result.try

function parseConfig(json: string): Result<Config, ParseError> {
  return Result.try({
    try: () => JSON.parse(json) as Config,
    catch: (cause) => new ParseError({ cause, message: `Parse failed: ${cause}` }),
  });
}

Async throws → Result.tryPromise

async function fetchUser(id: string): Promise<Result<User, ApiError | UnhandledException>> {
  return Result.tryPromise({
    try: async () => {
      const res = await fetch(`/api/users/${id}`);
      if (!res.ok) throw new ApiError({ status: res.status, message: `API ${res.status}` });
      return res.json() as Promise<User>;
    },
    catch: (cause) => (cause instanceof ApiError ? cause : new UnhandledException({ cause })),
  });
}

Null sentinel → Result

function findUser(id: string): Result<User, NotFoundError> {
  const user = users.find((candidate) => candidate.id === id);
  return user
    ? Result.ok(user)
    : Result.err(new NotFoundError({ id, message: `User ${id} not found` }));
}

Nested flow → Result.gen

async function processOrder(orderId: string): Promise<Result<OrderResult, OrderError>> {
  return Result.gen(async function* () {
    const order = yield* Result.await(fetchOrder(orderId));
    const validated = yield* validateOrder(order);
    const result = yield* Result.await(submitOrder(validated));
    return Result.ok(result);
  });
}

Execution Workflow

  1. Audit the target module for try, catch, .catch(...), throw, null, undefined, and status-flag error handling.
  2. Define or update TaggedError classes before changing control flow.
  3. Convert boundary functions first and change their signatures to Result<T, E> or Promise<Result<T, E>>.
  4. Update immediate callers so they handle or propagate the new Result.
  5. Where multiple Result-returning steps compose, use Result.gen or andThen.
  6. Preserve error context by keeping cause, IDs, messages, and other structured fields.
  7. Run tests and add coverage for both success and error paths.

Completion Criteria

A migration is complete when:

  • target functions no longer rely on try/catch for expected domain failures
  • nullable or sentinel error returns are replaced with explicit Result values
  • domain failures use typed TaggedError classes
  • callers either propagate Result or explicitly unwrap/match it
  • tests cover at least one success path and one representative error path

Common Pitfalls

  • Over-wrapping everything instead of starting at boundaries
  • Losing original failure context when mapping errors
  • Mixing throw-based and Result-based APIs deep in the same flow
  • Catching Panic instead of fixing the underlying defect

In This Reference

FilePurpose
references/tagged-errors.mdTaggedError patterns, matching, type guards, and examples

If opensrc/ exists, treat it as the source of truth for implementation details and current API behavior.

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

cloudflare

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

arxiv-paper-writer

Use this skill whenever the user wants Claude Code to write, scaffold, compile, debug, or review an arXiv-style academic paper, especially survey papers with LaTeX, BibTeX citations, TikZ figures, tables, and PDF output. This skill should trigger for requests like writing a full paper, creating an arXiv paper project, turning a research topic into a LaTeX manuscript, reproducing the Paper-Write-Skill-Test agent-survey workflow, or setting up a Windows/Linux Claude Code paper-writing loop.

Archived SourceRecently Updated
Coding

cli-proxy-troubleshooting

排查 CLI Proxy API(codex-api-proxy)的配置、认证、模型注册和请求问题。适用场景包括:(1) AI 请求报错 unknown provider for model, (2) 模型列表中缺少预期模型, (3) codex-api-key/auth-dir 配置不生效, (4) CLI Proxy 启动后 AI 无法调用, (5) 认证成功但请求失败或超时。包含源码级排查方法:模型注册表架构、认证加载链路、 SanitizeCodexKeys 规则、常见错误的真实根因。

Archived SourceRecently Updated
Coding

visual-summary-analysis

Performs AI analysis on input video clips/image content and generates a smooth, natural scene description. | 视觉摘要智述技能,对传入的视频片段/图片内容进行AI分析,生成一段通顺自然的场景描述内容

Archived SourceRecently Updated