function tryCatch
tryCatch<T, A extends readonly unknown[]>(
fn: (...args: A) => T,
...args: A
): Tried<T>

Calls fn(...args) and reflects the outcome into a Caught box — Result.try, shaped like Promise.try. See the module doc for the flat-classification pattern this is half of.

import { readFile } from 'node:fs/promises';
import * as Result from './index.ts';
const raw = '{"n": 1}';

const parsed = Result.try(JSON.parse, raw); // sync source → Result, synchronously
if (!parsed.ok && !(parsed.error instanceof SyntaxError)) throw parsed.error;

const read = await Result.try(() => readFile('config.json', 'utf8')); // async → Promise<Result>

Because it owns the call, the synchronous prefix of async work is inside the boundary too: Result.try(fetch, url) boxes the TypeError a malformed URL throws synchronously, which wrapping a pre-started fetch(url) promise never could.

Type Parameters

A extends readonly unknown[]

Parameters

fn: (...args: A) => T
...args: A

Return Type

Usage

import { tryCatch } from "lib/result/try.ts";