method Result.try
Result.try<T>(
fn: () => T,
context?: Record<string, unknown>
): Result<T, UnexpectedError>

Wraps a function that might throw into a Result.

Catches any exceptions and wraps them in UnexpectedError.

Examples

Example 1

const obj = Result.try(() =>
  typeof data === "string" ? JSON.parse(data) : data
);

const value = obj.take();
if (isErr(value)) {
  console.error("Parse failed:", value.error);
  return;
}
console.log(value); // parsed object

Type Parameters

The type of the return value

Parameters

fn: () => T

Function that might throw

optional
context: Record<string, unknown>

Optional context to add to the error

Return Type

Ok with the return value, or Err with UnexpectedError

Usage

import { Result } from "result/mod.ts";