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, and this page is available as Markdown at https://massaman.dev/reference/control/err.md.

err

Constructs a failure Result. Preserves specific Error types and normalizes non-Error values into Error.

const result = err(reason)

Usage

err(reason)

Pass an Error, a string, or any other value. Error instances are returned unchanged, including their specific subtype. Strings are wrapped in new Error(reason). Non-error, non-string values get JSON.stringify'd into the message and the original is preserved on error.cause.

import { err } from 'massaman'

err(new Error('boom'))
// { ok: false, value: null, error: Error('boom') }

err('division by zero')
// { ok: false, value: null, error: Error('division by zero') }

err({ code: 'EBADF', fd: 3 })
// { ok: false, value: null, error: Error('{"code":"EBADF","fd":3}', { cause: { code: 'EBADF', fd: 3 } }) }

Use a typed Error when callers need to map domain failures to HTTP responses:

type HttpError<Status extends number> = Error & { readonly status: Status }

const error: HttpError<404> = Object.assign(new Error('Spec not found'), {
  name: 'HttpError',
  status: 404 as const,
})

const result = err(error)
// Err<HttpError<404>>

Parameters

reasonunknownrequired

the failure value. Accepts anything — normalization to Error is the function's job.

Returns

Err<E> when given E extends Error; otherwise Err<Error>.

Err<E>

See also