jagreehal avatar

result-types

Never throw for expected failures. Use Result<T, E> types with explicit error handling and workflow

提供方 jagreehal|开源

Typed Errors: Never Throw

Critical rules

  • Expected failures return Result<T, E> — visible in the signature, exhaustively handled, composable.
  • Reserve throw / asserts for invariant violations and corrupted state only.
  • Compose fallible steps with createWorkflow / step (short-circuit on err). Bridge throws with step.try().
  • Map Results to HTTP in one shared boundary mapper — not per-handler ad hoc.
  • Enumerate every expected failure in E (no string / any). Group large unions by domain.
  • Before drafting examples or error shapes, read references/examples.md and references/patterns.md.

Workflow

  1. List expected failure modes for the function; choose string literals or discriminated unions.
  2. Return ok / err from core fn(args, deps) — catch infra exceptions at the edge of the function.
  3. Before chaining steps, read references/examples.md for step / step.try / step.fromResult.
  4. Compose with createWorkflow; keep business functions free of retry (use resilience).
  5. At the HTTP boundary, map errors via one status table. Exhaustive switch on result.error.
  6. If error unions grow large, group them — see references/patterns.md.

Resources

  • references/examples.md — Result shape, workflow, HTTP mapping, error type forms. Read when implementing.
  • references/patterns.md — grouping, when to throw/asserts, rationalizations. Read when designing error models.

Validation

  • Expected failures return Result<T, E>, not throwing Promise<T>
  • E enumerates every expected failure
  • Chains use createWorkflow / step; third-party throws bridged with step.try()
  • HTTP status mapping is shared and exhaustive
  • throw / asserts only for invariants / impossible states

Constraints

  • Do not return Result for programmer errors. Do not use null to signal distinct failures.
  • Related: fn-args-deps, validation-boundary, resilience, api-design, observability.