( zodErrorCode: string, params: Record<string, unknown> )
| 220 | * @returns Error code and parameters |
| 221 | */ |
| 222 | export function zodErrorToCode( |
| 223 | zodErrorCode: string, |
| 224 | params: Record<string, unknown> |
| 225 | ): { code: ErrorCode; params?: Record<string, string | number> } { |
| 226 | const { minimum, maximum, type, path } = params; |
| 227 | const field = Array.isArray(path) ? path.join(".") : undefined; |
| 228 | |
| 229 | switch (zodErrorCode) { |
| 230 | case "invalid_type": |
| 231 | if (type === "string" && params.received === "undefined") { |
| 232 | return { code: ERROR_CODES.REQUIRED_FIELD, params: { field: field || "field" } }; |
| 233 | } |
| 234 | return { code: ERROR_CODES.INVALID_TYPE, params: { field: field || "field" } }; |
| 235 | |
| 236 | case "too_small": |
| 237 | if (typeof minimum === "number") { |
| 238 | // 区分字符串长度和数值范围 |
| 239 | const isStringType = type === "string"; |
| 240 | return { |
| 241 | code: isStringType ? ERROR_CODES.MIN_LENGTH : ERROR_CODES.MIN_VALUE, |
| 242 | params: { field: field || "field", min: minimum }, |
| 243 | }; |
| 244 | } |
| 245 | return { code: ERROR_CODES.MIN_VALUE }; |
| 246 | |
| 247 | case "too_big": |
| 248 | if (typeof maximum === "number") { |
| 249 | // 区分字符串长度和数值范围 |
| 250 | const isStringType = type === "string"; |
| 251 | return { |
| 252 | code: isStringType ? ERROR_CODES.MAX_LENGTH : ERROR_CODES.MAX_VALUE, |
| 253 | params: { field: field || "field", max: maximum }, |
| 254 | }; |
| 255 | } |
| 256 | return { code: ERROR_CODES.MAX_VALUE }; |
| 257 | |
| 258 | case "invalid_string": |
| 259 | if (params.validation === "email") { |
| 260 | return { code: ERROR_CODES.INVALID_EMAIL }; |
| 261 | } |
| 262 | if (params.validation === "url") { |
| 263 | return { code: ERROR_CODES.INVALID_URL }; |
| 264 | } |
| 265 | return { code: ERROR_CODES.INVALID_FORMAT }; |
| 266 | |
| 267 | default: |
| 268 | return { code: ERROR_CODES.INVALID_FORMAT }; |
| 269 | } |
| 270 | } |
no outgoing calls
no test coverage detected