* 执行HTTP请求
(config)
| 141 | * 执行HTTP请求 |
| 142 | */ |
| 143 | async executeRequest(config) { |
| 144 | const controller = new AbortController(); |
| 145 | const timeoutId = setTimeout(() => controller.abort(), config.timeout); |
| 146 | |
| 147 | try { |
| 148 | const fetchOptions = { |
| 149 | method: config.method, |
| 150 | headers: config.headers, |
| 151 | signal: controller.signal |
| 152 | }; |
| 153 | |
| 154 | // 添加请求体 |
| 155 | if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(config.method) && config.body) { |
| 156 | if (typeof config.body === 'object') { |
| 157 | fetchOptions.body = JSON.stringify(config.body); |
| 158 | } else { |
| 159 | fetchOptions.body = config.body; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | const response = await fetch(config.url, fetchOptions); |
| 164 | clearTimeout(timeoutId); |
| 165 | |
| 166 | // 检查响应状态 |
| 167 | if (!response.ok) { |
| 168 | const errorData = await this.parseErrorResponse(response); |
| 169 | throw new APIError( |
| 170 | errorData.message || `HTTP ${response.status}`, |
| 171 | response.status, |
| 172 | errorData, |
| 173 | config.endpoint |
| 174 | ); |
| 175 | } |
| 176 | |
| 177 | // 解析响应 |
| 178 | const data = await this.parseResponse(response); |
| 179 | return data; |
| 180 | |
| 181 | } catch (error) { |
| 182 | clearTimeout(timeoutId); |
| 183 | |
| 184 | if (error.name === 'AbortError') { |
| 185 | throw new APIError('请求超时', 408, null, config.endpoint); |
| 186 | } |
| 187 | |
| 188 | if (error instanceof APIError) { |
| 189 | throw error; |
| 190 | } |
| 191 | |
| 192 | // 网络错误 |
| 193 | throw new APIError( |
| 194 | error.message || '网络请求失败', |
| 195 | 0, |
| 196 | null, |
| 197 | config.endpoint |
| 198 | ); |
| 199 | } |
| 200 | } |
no test coverage detected