refactor: better detection of ZodError (@fehmer) (#6258)

This commit is contained in:
Christian Fehmer 2025-02-11 20:16:09 +01:00 committed by GitHub
parent 60f664117f
commit a2d91f2a73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 6 deletions

View file

@ -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<T extends z.ZodTypeAny>(
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return schema.parse(jsonParsed) as z.infer<T>;
} 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;
}

12
packages/util/src/zod.ts Normal file
View file

@ -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;
}