core-utils
    Preparing search index...
    • Wraps a synchronous function that might throw into a ServiceResult. If the function executes successfully, returns a success ServiceResult. If the function throws, calls the onError function to convert the error into a ServiceError.

      Type Parameters

      • A

        The return type of the function

      Parameters

      • f: () => A

        The function to execute safely

      • onError: (error: unknown) => ServiceError

        Function to convert unknown errors into ServiceError

      Returns ServiceResult<A>

      A ServiceResult

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

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

      const successResult = tryCatch(
      () => parseJson<{ name: string }>('{"name": "John"}'),
      (error) => new ServiceError(`Parse error: ${String(error)}`),
      );

      ok(isSuccess(successResult));
      strictEqual(successResult.value.name, "John");

      const failureResult = tryCatch(
      () => parseJson("invalid json"),
      (error) => new ServiceError(`Parse error: ${String(error)}`),
      );

      ok(isFailure(failureResult));
      ok(failureResult.error.issues[0]?.message?.includes("Parse error"));