core-utils
    Preparing search index...
    • Converts a promise returning function into a ServiceResult by handling potential rejections. If the promise returning function resolves successfully, returns a success ServiceResult. If the promise rejects, calls the onError function to convert the error into a ServiceError.

      Type Parameters

      • A

        The type of the value the promise resolves to

      Parameters

      • f: () => Promise<A>

        Function returning a Promise to execute. Passing a function allows catching synchronous throws

      • onError: (error: unknown) => ServiceError

        Maps unknown errors to a ServiceError

      Returns Promise<ServiceResult<A>>

      A promise that resolves to a ServiceResult

      import { ok, strictEqual } from "node:assert/strict";

      import { isFailure, isSuccess, ServiceError, tryCatchAsync } from "@clipboard-health/util-ts";

      async function example() {
      const successResult = await tryCatchAsync(
      async () => {
      const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
      return (await response.json()) as { id: number };
      },
      (error) => new ServiceError(`Failed to fetch: ${String(error)}`),
      );

      ok(isSuccess(successResult));
      strictEqual(successResult.value.id, 1);

      const failureResult = await tryCatchAsync(
      async () => await Promise.reject(new Error("Network error")),
      (error) => new ServiceError(`Failed to fetch: ${String(error)}`),
      );

      ok(isFailure(failureResult));
      strictEqual(failureResult.error.issues[0]?.message, "Failed to fetch: Error: Network error");
      }

      // eslint-disable-next-line unicorn/prefer-top-level-await
      void example();