Skip to main content
Module

x/fun/mod.ts>promise.tryCatch

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

Wrap a function that potentially throws in a try/catch block, handling any thrown errors and returning the result inside of a Promise.

Examples

Example 1

import { tryCatch, reject, wrap } from "./promise.ts";
import { pipe, todo } from "./fn.ts";
// Note that todo will always throw synchronously.

const add = (n: number) => n + 1;
const throwSync = (_: number): number => todo();
const throwAsync = (_: number): Promise<number> => reject("Ha!");

const catchAdd = tryCatch(add, () => -1);
const catchSync = tryCatch(throwSync, () => -1);
const catchAsync = tryCatch(throwAsync, () => -1);

const resultAdd = await catchAdd(1); // 2
const resultSync = await catchSync(1); // -1
const resultAsync = await catchAsync(1); // -1

Type Parameters

D extends unknown[]
A

Parameters

handle: (...args: D) => A | PromiseLike<A>
onThrow: (error: unknown, args: D) => A

Returns

(...args: D) => Promise<A>