You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zod验证后端Booking数据时返回空ZodError数组,如何获取详细校验错误信息?

How to Get Detailed Zod Validation Errors & Fix Your Status Field Schema

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:

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 the status field)
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:42:45