Skip to main content
Module

x/fun/fn.ts>handleThrow

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

Wrap any function in a try catch block, passing the result and arguments to onResult when the function does not throw as well as passing the error and arguments to the onThrow function when it does. Neither the onResult nor the onThrow functions should ever throw an error themselves. None of the functions in the fun library will throw on their own. If they do it is a bug in fun or the underlying runtime (or you used fun in javascript). This function primarily exists to wrap functions exported from other libraries that may use exceptions as their error mechanism. This makes those functions safe to use with fun.

Examples

Example 1

import * as F from "./fn.ts";

const throwOverFive = (n: number): number => {
  if (n > 5) {
    throw new Error("Larger than five");
  }
  return n;
}
const caught = F.handleThrow(
  throwOverFive,
  result => result,
  err => 0, // Default to 0
);

const result1 = caught(0); // 0
const result2 = caught(5); // 5
const result3 = caught(6); // 0

Type Parameters

D extends unknown[]
A
I

Parameters

ua: (...d: D) => A
onResult: (result: A, args: D) => I
onThrow: (error: unknown, args: D) => I

Returns

(...d: D) => I