Skip to content

guard

Wraps a function so that if it throws, a default value is returned instead of propagating the error. Works with both synchronous and asynchronous functions.

Available since v2.0.0

import { guard } from '@helpers4/promise';
// or, from the all-in-one package (same code, one install):
import { guard } from 'helpers4/promise';
guard<T>(fn: function, defaultValue: T): Promise<T>
ParameterTypeDescription
fnfunctionThe function to guard
defaultValueTThe value to return if the function throws

Promise<T> — The result of the function, or the default value on error

Returns a default value when the function throws.

const result = guard(() => JSON.parse('invalid'), {})
// => {}

Returns the function result when it does not throw.

const result = guard(() => JSON.parse('{"a":1}'), {})
// => { a: 1 }

View source on GitHub