fix(api): raise on unsuccessful API responses - #1288
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1288 +/- ##
==========================================
+ Coverage 89.70% 90.37% +0.67%
==========================================
Files 48 48
Lines 4778 4718 -60
==========================================
- Hits 4286 4264 -22
+ Misses 492 454 -38 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
inimaz
left a comment
There was a problem hiding this comment.
Thanks for the PR @PSR94 . Unfortunately as you might have been in the issue, it is not enough with throwing the error, one has to go into the places where this client has been called (cli and emissionsTracker) and do a try-catch around them.
There is another PR related to this here --> #1277.
I see 2 options either you go and try-catch them or you wait until that PR does it and once merged resolve the conflicts and use your _request function. What do you think?
| headers["Authorization"] = f"Bearer {self.access_token}" | ||
| return headers | ||
|
|
||
| def _request(self, method, url, payload=None, expected_status=200): |
Every method repeated the same four lines: build the headers, call requests, compare the status code, log and raise. They now all delegate to a single `_request(method, url, payload, expected_status)`, which removes 44 lines from the module. Behaviour is unchanged: `_request` calls `_raise_api_error` on an unexpected status, so the errors raised, the logs and the re-raise clauses of `add_emission` and `_create_run` all stay as they were. The helper comes from the alternative fix proposed in mlco2#1288, which targets the same issue. Co-authored-by: PSR94 <88868390+PSR94@users.noreply.github.com> Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Summary
Make the CodeCarbon API client raise
requests.exceptions.HTTPErrorwhen the API returns an unexpected HTTP status, while preserving the existing tracker-facing output handling that catches upload failures.Why this helps
Callers can now distinguish API failures through standard
requestsexceptions instead of receivingNoneorFalsefrom failed HTTP responses. This supports clearer error handling while keeping emissions uploads from breaking tracker execution.Changes made
ApiClientthat logs API response details and callsraise_for_status().HTTPError.Testing
uv run pytest tests/test_api_call.py tests/output_methods/test_http.py -quv run ruff check codecarbon/core/api_client.py tests/test_api_call.py tests/output_methods/test_http.pyuv run black --check --diff codecarbon/core/api_client.py tests/test_api_call.py tests/output_methods/test_http.pyCODECARBON_ALLOW_MULTIPLE_RUNS=True uv run pytest --ignore=tests/test_viz_data.py -q -m 'not integ_test' tests/Closes #820