( toolName: string, error: ZodError, )
| 64 | * @returns A formatted error message string |
| 65 | */ |
| 66 | export function formatZodValidationError( |
| 67 | toolName: string, |
| 68 | error: ZodError, |
| 69 | ): string { |
| 70 | const missingParams = error.issues |
| 71 | .filter( |
| 72 | err => |
| 73 | err.code === 'invalid_type' && |
| 74 | err.message.includes('received undefined'), |
| 75 | ) |
| 76 | .map(err => formatValidationPath(err.path)) |
| 77 | |
| 78 | const unexpectedParams = error.issues |
| 79 | .filter(err => err.code === 'unrecognized_keys') |
| 80 | .flatMap(err => err.keys) |
| 81 | |
| 82 | const typeMismatchParams = error.issues |
| 83 | .filter( |
| 84 | err => |
| 85 | err.code === 'invalid_type' && |
| 86 | !err.message.includes('received undefined'), |
| 87 | ) |
| 88 | .map(err => { |
| 89 | const typeErr = err as { expected: string } |
| 90 | const receivedMatch = err.message.match(/received (\w+)/) |
| 91 | const received = receivedMatch ? receivedMatch[1] : 'unknown' |
| 92 | return { |
| 93 | param: formatValidationPath(err.path), |
| 94 | expected: typeErr.expected, |
| 95 | received, |
| 96 | } |
| 97 | }) |
| 98 | |
| 99 | // Default to original error message if we can't create a better one |
| 100 | let errorContent = error.message |
| 101 | |
| 102 | // Build a human-readable error message |
| 103 | const errorParts = [] |
| 104 | |
| 105 | if (missingParams.length > 0) { |
| 106 | const missingParamErrors = missingParams.map( |
| 107 | param => `The required parameter \`${param}\` is missing`, |
| 108 | ) |
| 109 | errorParts.push(...missingParamErrors) |
| 110 | } |
| 111 | |
| 112 | if (unexpectedParams.length > 0) { |
| 113 | const unexpectedParamErrors = unexpectedParams.map( |
| 114 | param => `An unexpected parameter \`${param}\` was provided`, |
| 115 | ) |
| 116 | errorParts.push(...unexpectedParamErrors) |
| 117 | } |
| 118 | |
| 119 | if (typeMismatchParams.length > 0) { |
| 120 | const typeErrors = typeMismatchParams.map( |
| 121 | ({ param, expected, received }) => |
| 122 | `The parameter \`${param}\` type is expected as \`${expected}\` but provided as \`${received}\``, |
| 123 | ) |
no test coverage detected