|
1 | 1 | """Main client for ProjectX Gateway API.""" |
2 | 2 |
|
3 | 3 | import logging |
4 | | -from typing import Any, Dict, Optional |
| 4 | +from typing import Any, Dict, Optional, cast |
5 | 5 |
|
6 | 6 | import requests |
7 | 7 |
|
@@ -217,27 +217,32 @@ def request( |
217 | 217 |
|
218 | 218 | # Parse the response |
219 | 219 | try: |
220 | | - data = response.json() |
| 220 | + json_data = response.json() |
221 | 221 | except ValueError: |
222 | 222 | raise RequestError(f"Invalid JSON response: {response.text}") |
223 | 223 |
|
| 224 | + # Defensive check: ensure we got a dictionary (handles None case for mypy) |
| 225 | + if json_data is None: |
| 226 | + raise ProjectXError("Received null response from API") |
| 227 | + |
| 228 | + # Safe to cast now that we've checked |
| 229 | + response_data: Dict[str, Any] = cast(Dict[str, Any], json_data) |
| 230 | + |
224 | 231 | # Check for API-level errors |
225 | | - if not data.get("success", True): |
226 | | - # Handle response data that might be None |
227 | | - if data is None: |
228 | | - error_code = 0 |
229 | | - error_message = "Unknown error" |
230 | | - else: |
231 | | - error_code = data.get("errorCode", 0) |
232 | | - error_message = data.get("errorMessage", "Unknown error") |
233 | | - |
| 232 | + success = response_data.get("success", True) # type: ignore[union-attr] |
| 233 | + if not success: |
| 234 | + error_code = response_data.get("errorCode", 0) # type: ignore[union-attr] |
| 235 | + err_msg = response_data.get( # type: ignore[union-attr] |
| 236 | + "errorMessage", "Unknown error" |
| 237 | + ) |
| 238 | + |
234 | 239 | raise ProjectXError( |
235 | | - f"API error {error_code}: {error_message}", |
236 | | - error_code=error_code, |
237 | | - response=data |
| 240 | + f"API error {error_code}: {err_msg}", |
| 241 | + error_code=error_code, |
| 242 | + response=response_data, |
238 | 243 | ) |
239 | 244 |
|
240 | | - return data # type: ignore |
| 245 | + return response_data |
241 | 246 |
|
242 | 247 | except requests.RequestException as e: |
243 | 248 | raise RequestError(f"Request failed: {str(e)}") |
|
0 commit comments