For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/control/attempt.md.

attempt

Executes a synchronous function and wraps the outcome in a Result, so callers can handle failure without try/catch.

const result = attempt(() => fn())

Usage

attempt(fn)

attempt is the canonical way to call a function that may throw — JSON parsing, schema validation, anything from a third-party API that doesn't itself return a Result. The thrown value is normalized to an Error (strings get wrapped; non-error values become an Error whose message is JSON.stringify(thrown) and whose cause is the original value).

import { attempt, isOk } from 'massaman'
// or:  import { attempt, isOk } from 'massaman/control'

const parsed = attempt(() => JSON.parse(input))
if (isOk(parsed)) {
  doSomething(parsed.value)
} else {
  console.error(parsed.error)
}

Parameters

fn() => Trequired

the function to execute. Must be synchronous — use attemptAsync for async work.

Returns

an Ok<T> on success, Err on throw.

Result<T>

Examples

Replace try/catch at the boundary of an unsafe API:

import { attempt, match, P } from 'massaman'

const result = attempt(() => JSON.parse(req.body))

return match(result)
  .with(P.ok(), ({ value }) => respond.ok(value))
  .with(P.err(), ({ error }) => respond.badRequest(error.message))
  .exhaustive()

See also