The return type of the function
The function to execute safely
Function to convert unknown errors into ServiceError
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"));
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.