(error: Error)
| 112 | |
| 113 | // Parse Agent Studio errors as they are returned as JSON rather than Markdown/text |
| 114 | export const getAgentStudioErrorMessage = (error: Error): Error => { |
| 115 | const raw = error.message; |
| 116 | |
| 117 | let parsed: unknown; |
| 118 | try { |
| 119 | parsed = JSON.parse(raw); |
| 120 | } catch { |
| 121 | const extracted = extractAgentStudioErrorFieldMessage(raw); |
| 122 | return new Error(extracted ?? raw); |
| 123 | } |
| 124 | |
| 125 | while (typeof parsed === 'string') { |
| 126 | try { |
| 127 | parsed = JSON.parse(parsed.trim()); |
| 128 | } catch { |
| 129 | const extracted = extractAgentStudioErrorFieldMessage(raw); |
| 130 | return new Error(extracted ?? (parsed as string)); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { |
| 135 | const extracted = extractAgentStudioErrorFieldMessage(raw); |
| 136 | return new Error(extracted ?? raw); |
| 137 | } |
| 138 | |
| 139 | const parsedError = parsed as Error & { |
| 140 | code?: string; |
| 141 | errorCode?: string; |
| 142 | message?: string; |
| 143 | error?: string; |
| 144 | }; |
| 145 | |
| 146 | if (parsedError.name === 'ValidationError') { |
| 147 | const validationError = parsedError as AgentStudioValidationError; |
| 148 | let errorMessage = raw; |
| 149 | if (validationError.detail && validationError.detail.length > 0) { |
| 150 | const { msg, loc } = validationError.detail[0]; |
| 151 | const field = loc.at(-1); |
| 152 | errorMessage = `${msg}: ${field}`; |
| 153 | } |
| 154 | return new Error(errorMessage); |
| 155 | } |
| 156 | |
| 157 | const extracted = extractAgentStudioErrorFieldMessage(raw); |
| 158 | let errorMessage: string; |
| 159 | if (extracted) { |
| 160 | errorMessage = extracted; |
| 161 | } else if (typeof parsedError.message === 'string' && parsedError.message.trim() !== '') { |
| 162 | errorMessage = parsedError.message.trim(); |
| 163 | } else if (typeof parsedError.error === 'string' && parsedError.error.trim() !== '') { |
| 164 | errorMessage = parsedError.error.trim(); |
| 165 | } else { |
| 166 | errorMessage = raw; |
| 167 | } |
| 168 | |
| 169 | const code = parsedError.code ?? parsedError.errorCode; |
| 170 | if (typeof code === 'string' && code.trim() !== '') { |
| 171 | const c = code.trim(); |
no test coverage detected