@pathmaker-digital/pmd-utilities - v2.2.6
    Preparing search index...

    Function attempt

    • Tries to execute a function and returns an object with the result of the attempt. If the function executes successfully, it returns the result inside an object with success: true. If an error is thrown, it returns the error inside an object with success: false.

      Type Parameters

      • T = unknown

      Parameters

      • fn: () => T

        The function to attempt to execute.

      Returns AttemptResult<T>

      An object containing success: true with the result if the function executes successfully, or success: false with the error if the function throws an error.

      // Successful execution
      const result = attempt(() => {
      return "Success!";
      });
      console.log(result); // { success: true, result: "Success!" }
      // Unsuccessful execution (throws error)
      const result = attempt(() => {
      throw new Error("Something went wrong");
      });
      console.log(result); // { success: false, error: Error("Something went wrong") }