Hi there! Are you looking for the official Deno documentation? Try docs.deno.com for all your Deno learning needs.

tryCatch

import { tryCatch } from "https://github.gh-proxy.cn/raw.githubusercontent.com/baetheus/fun/main/promise.ts";

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

@example
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
function tryCatch<D extends unknown[], A>(handle: (...args: D) => A | PromiseLike<A>, onThrow: (error: unknown, args: D) => A): (...args: D) => Promise<A>;
§
tryCatch<D extends unknown[], A>(handle: (...args: D) => A | PromiseLike<A>, onThrow: (error: unknown, args: D) => A): (...args: D) => Promise<A>
[src]

§Type Parameters

§
D extends unknown[]
[src]

§Parameters

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

§Return Type

§
(...args: D) => Promise<A>
[src]