错误
ts
const result = z.string().safeParse(12); // { success: false, error: ZodError }
result.error.issues;结果
ts
[
{
expected: "string",
code: "invalid_type",
path: [],
message: "Invalid input: expected string, received number",
},
];error map
ts
z.string({
error: (iss) => (iss.input === undefined ? "该字段为必填项。" : "无效输入。"),
});当 error 是一个函数的时候,这个函数就是 error map
iss 拥有多种类型
ts
iss.code; // 问题代码
iss.input; // 输入数据
iss.inst; // 产生该问题的模式/检查
iss.path; // 错误路径全局错误定制
ts
z.config({
customError: (issus) => {
const { path, code, expected, input } = issus;
const valName = path?.join("、");
if (input === undefined) {
return `缺少 ${valName}`;
}
return `${valName} 应该为 ${expected}`;
},
});