Skip to content

tryit

Wraps a function so it never throws. Instead, it returns a [error, result] tuple. Useful for avoiding try/catch blocks and handling errors in a functional style.

Available since v2.0.0

import { tryit } from '@helpers4/promise';
tryit<TArgs extends readonly unknown[], TReturn>(fn: function): function
ParameterTypeDescription
fnfunctionThe function to wrap (sync or async)

function — A new function that returns a Result tuple

Wraps JSON.parse to return a tuple instead of throwing.

const safeParse = tryit(JSON.parse);
const [error, data] = safeParse('{"a":1}');
// error === undefined, data === { a: 1 }

On error, the first element of the tuple is the Error.

const safeParse = tryit(JSON.parse);
const [error, data] = safeParse('invalid');
// error instanceof SyntaxError, data === undefined

View source on GitHub