Function protect

Protects a function from throwing errors by returning a Result object.

  • The success property indicates whether the function succeeded or not.
  • The data property contains the return value of the function if it succeeded.
  • The error property contains the error thrown by the function if it failed.
  • If the function returns a promise, the data and error properties will contain the resolved value and the rejected error respectively.
const okFn = () => 'ok';
const errorFn = () => { throw new Error('error') };
const okResult = protect(okFn)(); // { success: true, data: 'ok' }
const errorResult = protect(errorFn)(); // { success: false, error: Error('error') }
  • Type Parameters

    • A
    • R
    • T extends Promise<Result<Awaited<R<R>>>> | Result<R>

    Parameters

    • fn: (...args: A[]) => R

    Returns (...args: A[]) => T