Handle a response: check status, parse `ApiResponse `, unwrap data.
(
&self,
resp: reqwest::Response,
)
| 183 | |
| 184 | /// Handle a response: check status, parse `ApiResponse<T>`, unwrap data. |
| 185 | async fn handle_response<T: DeserializeOwned>( |
| 186 | &self, |
| 187 | resp: reqwest::Response, |
| 188 | ) -> Result<T, RemoteError> { |
| 189 | crate::check_min_version_header(resp.headers()); |
| 190 | let status = resp.status(); |
| 191 | let body = resp |
| 192 | .text() |
| 193 | .await |
| 194 | .map_err(|e| RemoteError::other(format!("failed to read response: {}", e)))?; |
| 195 | |
| 196 | if !status.is_success() { |
| 197 | return Err(self.parse_error_body(status.as_u16(), &body)); |
| 198 | } |
| 199 | |
| 200 | let api_resp: ApiResponse<T> = serde_json::from_str(&body).map_err(|e| { |
| 201 | let preview_len = body.len().min(200); |
| 202 | RemoteError::other(format!( |
| 203 | "invalid response JSON: {} (body: {})", |
| 204 | e, |
| 205 | &body[..preview_len] |
| 206 | )) |
| 207 | })?; |
| 208 | |
| 209 | if !api_resp.success { |
| 210 | if let Some(err) = api_resp.error { |
| 211 | return Err(RemoteError::other(format!("{}: {}", err.code, err.message))); |
| 212 | } |
| 213 | return Err(RemoteError::other("request failed with no error details")); |
| 214 | } |
| 215 | |
| 216 | api_resp |
| 217 | .data |
| 218 | .ok_or_else(|| RemoteError::other("response had success=true but no data")) |
| 219 | } |
| 220 | |
| 221 | fn parse_error_body(&self, status: u16, body: &str) -> RemoteError { |
| 222 | // Try to parse as ApiResponse first. |
no test coverage detected