( error: unknown, authType?: AuthType, userTier?: UserTierId, currentModel?: string, fallbackModel?: string, )
| 101 | } |
| 102 | |
| 103 | export function parseAndFormatApiError( |
| 104 | error: unknown, |
| 105 | authType?: AuthType, |
| 106 | userTier?: UserTierId, |
| 107 | currentModel?: string, |
| 108 | fallbackModel?: string, |
| 109 | ): string { |
| 110 | if (isStructuredError(error)) { |
| 111 | let text = `[API Error: ${error.message}]`; |
| 112 | if (error.status === 429) { |
| 113 | text += getRateLimitMessage( |
| 114 | authType, |
| 115 | error, |
| 116 | userTier, |
| 117 | currentModel, |
| 118 | fallbackModel, |
| 119 | ); |
| 120 | } |
| 121 | return text; |
| 122 | } |
| 123 | |
| 124 | // The error message might be a string containing a JSON object. |
| 125 | if (typeof error === 'string') { |
| 126 | const jsonStart = error.indexOf('{'); |
| 127 | if (jsonStart === -1) { |
| 128 | return `[API Error: ${error}]`; // Not a JSON error, return as is. |
| 129 | } |
| 130 | |
| 131 | const jsonString = error.substring(jsonStart); |
| 132 | |
| 133 | try { |
| 134 | const parsedError = JSON.parse(jsonString) as unknown; |
| 135 | if (isApiError(parsedError)) { |
| 136 | let finalMessage = parsedError.error.message; |
| 137 | try { |
| 138 | // See if the message is a stringified JSON with another error |
| 139 | const nestedError = JSON.parse(finalMessage) as unknown; |
| 140 | if (isApiError(nestedError)) { |
| 141 | finalMessage = nestedError.error.message; |
| 142 | } |
| 143 | } catch (_e) { |
| 144 | // It's not a nested JSON error, so we just use the message as is. |
| 145 | } |
| 146 | let text = `[API Error: ${finalMessage} (Status: ${parsedError.error.status})]`; |
| 147 | if (parsedError.error.code === 429) { |
| 148 | text += getRateLimitMessage( |
| 149 | authType, |
| 150 | parsedError, |
| 151 | userTier, |
| 152 | currentModel, |
| 153 | fallbackModel, |
| 154 | ); |
| 155 | } |
| 156 | return text; |
| 157 | } |
| 158 | } catch (_e) { |
| 159 | // Not a valid JSON, fall through and return the original message. |
| 160 | } |
no test coverage detected