Zod验证后端Booking数据时返回空ZodError数组,如何获取详细校验错误信息?
Let's work through your two key problems here: fixing the broken status schema definition, and getting clear, detailed error messages from Zod instead of that empty array you're seeing.
1. Fix the Status Field Schema
Your current status line has a critical JavaScript logic mistake:
status: z.literal("pending" || "confirmed" || "closed"),
In JavaScript, "pending" || "confirmed" || "closed" evaluates to just "pending" (it returns the first truthy value in the OR chain). That means your schema only accepts "pending" as a valid status—any "confirmed" or "closed" values from the backend will fail validation, and missing status fields will also trigger errors (since Zod marks fields as required by default).
To fix this properly, use Zod's enum type, which is built for exactly this scenario:
status: z.enum(["pending", "confirmed", "closed"]),
If the backend might sometimes omit the status field (and you want to allow that), add .optional():
status: z.enum(["pending", "confirmed", "closed"]).optional(),
Or if you want to set a default value when status is missing:
status: z.enum(["pending", "confirmed", "closed"]).default("pending"),
2. Capture Detailed Validation Errors
The empty error array you're seeing is because you're using parse(), which throws a ZodError, but you're not accessing the actual error details stored in the issues property of that error object.
You have two good options to fix this:
Option 1: Use safeParse() (Recommended for Controlled Error Handling)
Instead of parse(), use safeParse() which returns a result object (no throw by default) so you can inspect errors directly:
export function bookingOnLoadValidator(bookingArray: unknown) { const validationResult = bookingOnLoadResponse.safeParse(bookingArray); if (!validationResult.success) { // Log the full detailed error issues console.error("Booking validation failed:", validationResult.error.issues); // You can throw the error if you need it to propagate, or handle it here throw validationResult.error; } return validationResult.data; }
Option 2: Catch the ZodError Explicitly
If you prefer to keep using parse(), catch the error and log its issues property:
import { z } from "zod"; // Make sure you import z export function bookingOnLoadValidator(bookingArray: unknown) { try { return bookingOnLoadResponse.parse(bookingArray); } catch (err) { if (err instanceof z.ZodError) { console.error("Validation errors:", err.issues); } throw err; // Re-throw to let the error propagate if needed } }
The issues array will give you specific details for each failure, like:
path: The exact location of the error (e.g.,[0, "status"]means the first booking in the array is missing thestatusfield)message: A human-readable explanation (e.g., "Required" for missing fields, or "Invalid literal value, expected 'pending', 'confirmed', or 'closed'" for wrong status values)code: A machine-readable error code (like"required"or"invalid_literal")
This will make it immediately clear why validation is failing, whether it's missing fields, wrong values, or type mismatches.
内容的提问来源于stack exchange,提问作者seven

