Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

715 B
Raw Blame
/** JSON parsing without throws at an input boundary. */
export type SafeJsonParseResult =
  | { readonly ok: true; readonly value: unknown }
  | { readonly ok: false; readonly error: string; readonly cause: unknown };

/** Parse JSON text, returning the failure reason instead of throwing. */
export const safeParseJson = (
  value: string,
  reviver?: (
    key: string,
    value: unknown,
    context?: { readonly source?: string },
  ) => unknown,
): SafeJsonParseResult => {
  try {
    return { ok: true, value: JSON.parse(value, reviver) as unknown };
  } catch (cause: unknown) {
    return {
      ok: false,
      error: cause instanceof Error ? cause.message : String(cause),
      cause,
    };
  }
};