diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a32479..91eda8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht - Preserve the API Call ID on SDK errors raised while waiting for a call result, so callers can resume querying the same call after a connection failure, API error, or timeout. The create-and-wait example accepts `--call-id` to resume. +- Map malformed or non-JSON API responses to the SDK's stable error hierarchy + instead of leaking a JSON decoder exception to callers. ## [1.0.1] - 2026-09-23 diff --git a/src/calle/calls.py b/src/calle/calls.py index 254cbd8..4e82a5e 100644 --- a/src/calle/calls.py +++ b/src/calle/calls.py @@ -4,7 +4,7 @@ import httpx -from calle.errors import CalleAPIError, CalleConnectionError, CalleTimeoutError, api_error_from_response +from calle.errors import CalleAPIError, CalleConnectionError, CalleTimeoutError, response_payload JsonObject = dict[str, Any] @@ -84,9 +84,7 @@ def _request(self, method: str, path: str, **kwargs: Any) -> JsonObject: except httpx.HTTPError as exc: raise CalleConnectionError("CALL-E API request failed before receiving a response.") from exc - if response.status_code >= 400: - raise api_error_from_response(response.status_code, response.json()) - payload = response.json() + payload = response_payload(response) if not isinstance(payload, dict): raise CalleConnectionError("CALL-E API returned a non-object JSON response.") return payload diff --git a/src/calle/errors.py b/src/calle/errors.py index a8d8d6e..db0fe2c 100644 --- a/src/calle/errors.py +++ b/src/calle/errors.py @@ -1,5 +1,7 @@ from typing import Any +import httpx + class CalleAPIError(Exception): call_id: str | None = None @@ -40,6 +42,20 @@ class CalleWebhookSignatureError(Exception): pass +def response_payload(response: httpx.Response) -> object: + """Decode one API response without leaking JSON implementation errors.""" + try: + payload = response.json() + except ValueError as exc: + if response.status_code >= 400: + raise api_error_from_response(response.status_code, {}) from exc + raise CalleConnectionError("CALL-E API returned invalid JSON.") from exc + + if response.status_code >= 400: + raise api_error_from_response(response.status_code, payload) + return payload + + def api_error_from_response(status_code: int, payload: object) -> CalleAPIError: envelope = payload if isinstance(payload, dict) else {} raw_error = envelope.get("error") diff --git a/src/calle/goals.py b/src/calle/goals.py index 6d3854d..142446b 100644 --- a/src/calle/goals.py +++ b/src/calle/goals.py @@ -5,7 +5,7 @@ import httpx -from calle.errors import CalleConnectionError, CalleTimeoutError, api_error_from_response +from calle.errors import CalleConnectionError, CalleTimeoutError, response_payload JsonObject = dict[str, Any] @@ -130,9 +130,7 @@ def _request(self, method: str, path: str, **kwargs: Any) -> JsonObject: except httpx.HTTPError as exc: raise CalleConnectionError("CALL-E API request failed before receiving a response.") from exc - if response.status_code >= 400: - raise api_error_from_response(response.status_code, response.json()) - payload = response.json() + payload = response_payload(response) if not isinstance(payload, dict): raise CalleConnectionError("CALL-E API returned a non-object JSON response.") return payload diff --git a/tests/test_response_errors.py b/tests/test_response_errors.py new file mode 100644 index 0000000..0412f51 --- /dev/null +++ b/tests/test_response_errors.py @@ -0,0 +1,86 @@ +from collections.abc import Callable + +import httpx +import pytest + +from calle import CalleClient +from calle.errors import CalleAPIError, CalleConnectionError + + +Operation = Callable[[CalleClient], object] + + +@pytest.mark.parametrize( + "operation", + [ + lambda client: client.calls.get("call_123"), + lambda client: client.goals.get("goal_123"), + ], +) +def test_non_json_error_response_preserves_http_status(operation: Operation) -> None: + def handle_request(_request: httpx.Request) -> httpx.Response: + return httpx.Response( + 502, + text="Bad Gateway", + headers={"content-type": "text/html"}, + ) + + with httpx.Client( + base_url="https://api.heycall-e.com", + transport=httpx.MockTransport(handle_request), + ) as http_client: + client = CalleClient(api_key="key_test", http_client=http_client) + with pytest.raises(CalleAPIError) as exc_info: + operation(client) + + assert exc_info.value.status_code == 502 + assert exc_info.value.code == "internal_error" + assert exc_info.value.call_id is None + assert isinstance(exc_info.value.__cause__, ValueError) + + +def test_non_json_polling_error_keeps_status_and_call_id() -> None: + def handle_request(_request: httpx.Request) -> httpx.Response: + return httpx.Response( + 502, + text="Bad Gateway", + headers={"content-type": "text/html"}, + ) + + with httpx.Client( + base_url="https://api.heycall-e.com", + transport=httpx.MockTransport(handle_request), + ) as http_client: + client = CalleClient(api_key="key_test", http_client=http_client) + with pytest.raises(CalleAPIError) as exc_info: + client.calls.wait_for_result("call_123") + + assert exc_info.value.status_code == 502 + assert exc_info.value.call_id == "call_123" + assert isinstance(exc_info.value.__cause__, ValueError) + + +@pytest.mark.parametrize( + "operation", + [ + lambda client: client.calls.get("call_123"), + lambda client: client.goals.get("goal_123"), + ], +) +def test_non_json_success_response_maps_to_connection_error(operation: Operation) -> None: + def handle_request(_request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + content=b"not-json", + headers={"content-type": "text/plain"}, + ) + + with httpx.Client( + base_url="https://api.heycall-e.com", + transport=httpx.MockTransport(handle_request), + ) as http_client: + client = CalleClient(api_key="key_test", http_client=http_client) + with pytest.raises(CalleConnectionError, match="invalid JSON") as exc_info: + operation(client) + + assert isinstance(exc_info.value.__cause__, ValueError)