Last active
November 21, 2023 23:12
-
-
Save Thinkscape/d85d761335aa73ea0db59845d6aa9f1f to your computer and use it in GitHub Desktop.
Recursively convert ZodError to a string, or array of issue descriptions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: