@grafctory/core - v0.15.0
    Preparing search index...

    Function safe

    • Executes a task, absorbing its failures.

      Turns a failure the caller is prepared to ignore into an undefined result, so the computation stays a single expression instead of splitting into a try/catch statement. The result composes with opt, which maps it or closes the failure case with a fallback, supplied either outright or computed only when the task fails.

      Any other value is returned unchanged, null included. A task that returns undefined cannot be told apart from a failed one, so absorbing failures suits only tasks whose successful results are always defined.

      Important

      Only synchronous failures are absorbed. A rejected promise returned by the task is passed on unchanged, and its failure is to be handled with .catch() on the promise itself, or by awaiting it inside a try/catch statement.

      Type Parameters

      • R

        The type of the value returned by task

      Parameters

      • task: () => R

        The task to execute

      Returns Optional<R>

      The value returned by task, or undefined if task throws, whatever was thrown

      safe(() => JSON.parse(text)); // parsed value or undefined (malformed text)
      opt(safe(() => new URL(href)), url => url.host, "localhost"); // string (the fallback if href is malformed)