ts-fortress
    Preparing search index...

    Variable fromThrowableConst

    fromThrowable: <T>(fn: () => T) => Result<T, Error>

    Wraps a function that may throw an exception in a Result.

    This is a fundamental utility for converting traditional exception-based error handling into Result-based error handling. Any thrown value is converted to an Error object for consistent error handling. A PanicError (thrown by panic or the unwrap functions) is rethrown instead: a bug is not a recoverable failure.

    If the function executes successfully, returns Result.Ok with the result. If the function throws, returns Result.Err with the caught error.

    Type Declaration

      • <T>(fn: () => T): Result<T, Error>
      • Type Parameters

        • T

          The return type of the function.

        Parameters

        • fn: () => T

          The function to execute that may throw.

        Returns Result<T, Error>

        A Result<T, Error> containing either the successful result or the caught error.

    const success = Result.fromThrowable(() => 1 + 1);

    const failure = Result.fromThrowable(() => {
    throw new Error('boom');
    });

    assert.deepStrictEqual(success, Result.ok(2));

    assert.isTrue(Result.isErr(failure));