Skip to content

Variable: fromTry()

readonly fromTry: {<T>(executor): Result<T, Error>; <T, E>(executor, onError): Result<T, E>; }

Defined in: core/factories.ts:115

Call Signature

<T>(executor): Result<T, Error>

Wraps function execution in a Result, capturing exceptions.

Converts code that may throw exceptions into a Result, allowing explicit error handling without try/catch.

Type Parameters

T

T

Return value type

Parameters

executor

() => T

Function to execute

Returns

Result<T, Error>

Ok with return value or Err if throws exception

Examples

ts
// JSON parsing
const data = Result.fromTry(() => JSON.parse('{"name":"John"}'))
// Ok({name: "John"})

const invalid = Result.fromTry(() => JSON.parse('invalid json'))
// Err(SyntaxError: ...)
ts
// Operations that can fail
const result = Result.fromTry(() => {
  const file = readFileSync('config.json', 'utf-8')
  return JSON.parse(file)
})

Call Signature

<T, E>(executor, onError): Result<T, E>

Wraps function execution in Result with custom error transformation.

Type Parameters

T

T

Return value type

E

E

Error type

Parameters

executor

() => T

Function to execute

onError

(error) => E

Function that transforms the caught exception

Returns

Result<T, E>

Ok with return or Err with custom error

Examples

ts
// Custom typed error
type ParseError = { type: 'parse_error'; input: string }
const result = Result.fromTry(
  () => JSON.parse(input),
  (): ParseError => ({ type: 'parse_error', input })
)
ts
// Enriching the error
const config = Result.fromTry(
  () => loadConfig(),
  (err) => new Error(`Failed to load config: ${err}`)
)