@nevware21/ts-utils
    Preparing search index...

    Function safeGet

    • Function to safely execute a callback function, if the function throws the provided default value will be returned.

      Type Parameters

      • T = boolean
      • F extends (...args: any[]) => T = () => T

      Parameters

      • cb: F

        Callback function be wrapped with an exception

      • defValue: T

        The default value to return when an exception is thrown

      • OptionalargArray: Parameters<F>

        An optional array of arguments to be passed to the callback function (since 0.12.3)

      Returns T

      The result of the callback function or the default if an exception occurred calling the callback function.

      0.9.5

      let theExpression = "{ invalid: json value";

      let result = safeGet(() => {
      return JSON.parse(theExpression);
      }, {});

      // result === {};

      // Example with arguments

      let result = safeGet((id: number, name: string) => {
      if (id <= 0) {
      throw new Error("Invalid ID");
      }
      return { id, name };
      }, { id: 0, name: "default" }, [-1, "test"]);

      // result === { id: 0, name: "default" };

      // Example with arguments successfully used

      const result = safeGet((a: number, b: number) => {
      return a + b;
      }, 0, [5, 10]);

      // result === 15

      // Example accessing nested properties safely

      const config = { database: null };

      const connectionString = safeGet(() => {
      return config.database.connectionString;
      }, "default_connection");

      // Since config.database is null, accessing connectionString would throw
      // connectionString === "default_connection"