Skip to content

safeTry

Executes a function and captures any thrown errors as a failed ParseResult<T>. This helper provides a safe, zero-throwing wrapper around code that may throw, converting exceptions into structured, predictable results.

It never throws and never mutates input.

Signature

function safeTry<T>(fn: () => T): ParseResult<T>

Parameters

Returns

  • ok(value): When the function completes successfully.
  • error(message): When the function throws.

Behavior

  • Never throws.
  • Converts thrown Error objects into their .message.
  • Converts thrown non-Error values (string, number, etc.) into strings.
  • Never mutates input.
  • Ensures consistent result structure across all execution paths.

Examples

safeTry(() => 123)
// { ok: true, value: 123, issues: [] }

safeTry(() => { throw new Error("boom") })
// { ok: false, value: null, issues: ["boom"] }

safeTry(() => { throw "bad" })
// { ok: false, value: null, issues: ["bad"] }

Notes

  • safeTry is ideal for wrapping code that may throw, such as JSON parsing, URL construction, or domain-specific logic.
  • Helps maintain Jane’s zero-throwing, clarity-first workflow philosophy.