unthrown icon indicating copy to clipboard operation
unthrown copied to clipboard

Add a synchronous counterpart to fromSafePromise (fromSafeThrowable)

Open btravers opened this issue 4 months ago • 0 comments

Summary

Add a synchronous counterpart to fromSafePromise — a fromThrowable variant where every thrown value becomes a Defect, with no qualify callback. Working name: fromSafeThrowable (or fromSafe).

Motivation — real-world evidence

fromSafePromise exists precisely for "this async work has no modeled failures; every rejection is a Defect." There is no sync equivalent, so wrapping a throwing synchronous function whose every throw is a defect requires spelling out a throwaway qualify callback:

fromThrowable(
  () => decode(row),                  // sync, can throw
  (cause, defect) => defect(cause),   // <- pure boilerplate
)()

This (cause, defect) => defect(cause) incantation showed up verbatim across a large Boxed→unthrown migration (e.g. a repository mapper where a schema-decode/parse throw must land in the Defect channel while not-found is a modeled Err).

The asymmetry is stark:

direction "all failures are defects" helper
async fromSafePromise(promise) ✅
sync (none) — must write fromThrowable(fn, (c, d) => d(c))

Proposal

const parse = fromSafeThrowable(() => JSON.parse(s)); // (…args) => Result<T, never>
parse();                                              // Result<T, never> (throw -> Defect)
  • E = never (mirrors fromSafePromise, which yields AsyncResult<T, never>).
  • Same "returns a wrapped function you then call" shape as fromThrowable.
  • Keeps qualification mandatory in the general fromThrowable — this is the explicit, named "I've decided everything here is a defect" escape hatch, exactly as fromSafePromise is for promises.

Related: #77 (deliberate-defect ergonomics) — a fromSafeThrowable(...).toAsync() would also shorten that workaround.

btravers avatar Jul 08 '26 22:07 btravers