Skip to main content
Module

x/fun/mod.ts>option.tryCatch

A collection of algebraic data types, lenses, and schemables based on a light weight higher kinded type implementation. Written for deno.
Latest
function option.tryCatch
import { option } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { tryCatch } = option;

Take a function that can throw and wrap it in a try/catch block. Returns a new function that takes the same arguments as the original but returns the original value wrapped in an Option. If the function throws then the new function returns None, otherwise it returns Some.

Examples

Example 1

import * as O from "./option.ts";

function thrower(n: number): number {
  if (n < 0) {
    throw new Error("This number is too small");
  }
  return n;
}

const handler = O.tryCatch(thrower);

const result1 = handler(-1); // None
const result2 = handler(0); // Some(0);

Type Parameters

D extends unknown[]
A

Parameters

fn: (...d: D) => A

Returns

(...d: D) => Option<A>