Skip to content

Commit 3d4d780

Browse files
author
mozmo15
committed
fix(server): prioritize custom zod errors and format them
1 parent 671df6a commit 3d4d780

1 file changed

Lines changed: 26 additions & 6 deletions

File tree

packages/core/src/util/zodCompat.ts

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -187,23 +187,43 @@ export function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | un
187187
return undefined;
188188
}
189189

190+
function getDotPath(path: (string | number)[]) {
191+
if (path.length === 0) {
192+
return 'object root';
193+
}
194+
return path.reduce((acc, seg, index) => {
195+
if (index === 0) {
196+
return String(seg);
197+
}
198+
if (typeof seg === 'number') {
199+
return `${acc}[${seg}]`;
200+
}
201+
return `${acc}.${seg}`;
202+
}, '');
203+
}
204+
190205
// --- Error message extraction ---
191206
/**
192207
* Safely extracts an error message from a parse result error.
193208
* Zod errors can have different structures, so we handle various cases.
194209
*/
195210
export function getParseErrorMessage(error: unknown): string {
196211
if (error && typeof error === 'object') {
212+
// When present, prioritize zod issues and format as a message and path
213+
if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {
214+
return error.issues
215+
.map((i: { message: string; path?: (string | number)[] }) => {
216+
if(!i.path) {
217+
return i.message;
218+
}
219+
return `${i.message} at ${getDotPath(i.path)}`;
220+
})
221+
.join('\n');
222+
}
197223
// Try common error structures
198224
if ('message' in error && typeof error.message === 'string') {
199225
return error.message;
200226
}
201-
if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {
202-
const firstIssue = error.issues[0];
203-
if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {
204-
return String(firstIssue.message);
205-
}
206-
}
207227
// Fallback: try to stringify the error
208228
try {
209229
return JSON.stringify(error);

0 commit comments

Comments
 (0)