* 处理 HTTP 响应
(response: Response)
| 187 | * 处理 HTTP 响应 |
| 188 | */ |
| 189 | private async handleResponse<T>(response: Response): Promise<T> { |
| 190 | // 处理 204 No Content |
| 191 | if (response.status === 204) { |
| 192 | return undefined as T; |
| 193 | } |
| 194 | |
| 195 | // 尝试解析 JSON |
| 196 | const text = await response.text(); |
| 197 | let data: any; |
| 198 | |
| 199 | try { |
| 200 | data = text ? JSON.parse(text) : undefined; |
| 201 | } catch (error) { |
| 202 | // 不是有效的 JSON |
| 203 | if (!response.ok) { |
| 204 | throw new Error(`HTTP ${response.status}: ${text || response.statusText}`); |
| 205 | } |
| 206 | return text as T; |
| 207 | } |
| 208 | |
| 209 | // 检查错误 |
| 210 | if (!response.ok) { |
| 211 | const errorMessage = data?.error || data?.message || response.statusText; |
| 212 | throw new Error(`HTTP ${response.status}: ${errorMessage}`); |
| 213 | } |
| 214 | |
| 215 | // 解包 {success: true, data: {...}} 格式的响应 |
| 216 | if (data && typeof data === "object" && "success" in data && "data" in data) { |
| 217 | return data.data as T; |
| 218 | } |
| 219 | |
| 220 | return data as T; |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * 判断状态码是否应该重试 |