> For AI agents: the complete documentation index is available at https://massaman.dev/llms.txt, the full documentation bundle is available at https://massaman.dev/llms-full.txt.

# attempt

Executes a synchronous function and wraps the outcome in a [`Result`](https://massaman.dev/concepts/result.md), so callers can handle failure without `try`/`catch`.

```typescript
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).

```typescript
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`](https://massaman.dev/reference/control/attemptAsync.md) for async work.

#### Returns

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

```typescript
Result<T>
```

## Examples

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

```typescript
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

- [`attemptAsync`](https://massaman.dev/reference/control/attemptAsync.md) — async variant
- [`ok`](https://massaman.dev/reference/control/ok.md) / [`err`](https://massaman.dev/reference/control/err.md) — construct results manually
- [`unwrap`](https://massaman.dev/reference/control/unwrap.md) — extract or throw
- [`P.ok`](https://massaman.dev/reference/match/P.md#pok) / [`P.err`](https://massaman.dev/reference/match/P.md#perr) — patterns for `match`
- [Result & Errors concept guide](https://massaman.dev/concepts/result.md)
