* 解析 API 响应 * @param {Object} response * @returns {Object}
(response)
| 381 | * @returns {Object} |
| 382 | */ |
| 383 | parseResponse(response) { |
| 384 | const { statusCode, data } = response; |
| 385 | |
| 386 | // 处理 HTTP 错误 |
| 387 | if (statusCode !== 200) { |
| 388 | const errorInfo = this.parseErrorResponse(statusCode, data); |
| 389 | throw new GeminiError( |
| 390 | errorInfo.type, |
| 391 | errorInfo.message, |
| 392 | { statusCode, response: data.substring(0, 500) } |
| 393 | ); |
| 394 | } |
| 395 | |
| 396 | // 解析 JSON |
| 397 | let jsonData; |
| 398 | try { |
| 399 | jsonData = JSON.parse(data); |
| 400 | } catch (error) { |
| 401 | throw new GeminiError( |
| 402 | ErrorTypes.PARSE_ERROR, |
| 403 | 'Failed to parse API response', |
| 404 | { error: error.message, data: data.substring(0, 500) } |
| 405 | ); |
| 406 | } |
| 407 | |
| 408 | // 验证响应结构 |
| 409 | if (!jsonData.candidates || !jsonData.candidates[0] || !jsonData.candidates[0].content) { |
| 410 | throw new GeminiError( |
| 411 | ErrorTypes.INVALID_RESPONSE, |
| 412 | 'Invalid response structure', |
| 413 | { structure: Object.keys(jsonData) } |
| 414 | ); |
| 415 | } |
| 416 | |
| 417 | return jsonData.candidates[0].content.parts[0].text; |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * 解析错误响应 |
no test coverage detected