diff --git a/packages/util/src/json.ts b/packages/util/src/json.ts index fc1dc9a30..811fcfdbd 100644 --- a/packages/util/src/json.ts +++ b/packages/util/src/json.ts @@ -1,4 +1,5 @@ -import { z, ZodError, ZodIssue } from "zod"; +import { z, ZodIssue } from "zod"; +import { isZodError } from "./zod"; /** * Parse a JSON string into an object and validate it against a schema @@ -16,11 +17,8 @@ export function parseWithSchema( // eslint-disable-next-line @typescript-eslint/no-unsafe-return return schema.parse(jsonParsed) as z.infer; } catch (error) { - // instanceof ZodError is not working from our module - if ((error as ZodError)["issues"] !== undefined) { - throw new Error( - (error as ZodError).issues.map(prettyErrorMessage).join("\n") - ); + if (isZodError(error)) { + throw new Error(error.issues.map(prettyErrorMessage).join("\n")); } else { throw error; } diff --git a/packages/util/src/zod.ts b/packages/util/src/zod.ts new file mode 100644 index 000000000..4ad256588 --- /dev/null +++ b/packages/util/src/zod.ts @@ -0,0 +1,12 @@ +import { ZodError } from "zod"; + +//from https://github.com/colinhacks/zod/pull/3819 +export function isZodError(error: unknown): error is ZodError { + if (!(error instanceof Error)) return false; + + if (error instanceof ZodError) return true; + if (error.constructor.name === "ZodError") return true; + if ("issues" in error && error.issues instanceof Array) return true; + + return false; +}