Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active November 21, 2023 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thinkscape/d85d761335aa73ea0db59845d6aa9f1f to your computer and use it in GitHub Desktop.
Save Thinkscape/d85d761335aa73ea0db59845d6aa9f1f to your computer and use it in GitHub Desktop.
Recursively convert ZodError to a string, or array of issue descriptions.
import { type ZodError, type ZodIssue } from "zod";
export function zodErrorToString(error: ZodError, separator = ", ") {
return zodIssuesToStrings(error.issues).join(separator);
}
function zodIssuesToStrings(obj: ZodIssue[]) {
let results: string[] = [];
function traverse(node: ZodIssue | ZodIssue[]) {
if (!Array.isArray(node)) {
if (node.path && Array.isArray(node.path) && node.message) {
results.push(
`${node.path.length ? node.path.join(".") + ": " : ""}${
node.message
}`,
);
}
}
// Recursively traverse through arrays and objects to cover for issues in z.union() et. al.
for (let key in node) {
if (
typeof (node as never as Record<string, unknown>)[key] === "object" &&
(node as never as Record<string, unknown>)[key] !== null
) {
traverse(node[key as never]);
}
}
}
// Start traversing from the root object
traverse(obj);
return results;
}
@Thinkscape
Copy link
Author

Usage:

const zodSchema = z.object({ ... });
const data = { ... };

try {
  const result = zodSchema.parse(data);
} catch (error) {
  if (error instanceof ZodError) {
    console.error("Validation error: ", zodErrorToString(error));
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment