Skip to content

Commit ee61dc1

Browse files
fix(client): handle REST error bodies that are not a google.rpc.Status (a2aproject#1300)
# Description `RestTransport` raised `AttributeError` for HTTP errors whose JSON body is not a `google.rpc.Status` object (a proxy's `{"error": "invalid_token"}`, a string, a list, `null`), so the status-based fallback (`MethodNotFoundError` for 404, `A2AClientError` otherwise) never ran. The v0.3 compat REST transport had the same problem. - `_parse_rest_error` now returns `None` unless the payload is an object whose `error` is an object; the caller then uses the existing HTTP-status fallback. Well-formed `google.rpc.Status` bodies map exactly as before. - `CompatRestTransport._handle_http_error` treats a non-object body like an unparseable one. - Regression tests for both transports (401/404/5xx with string, list, `null` and string-valued `error` bodies). They fail on main with `AttributeError` and pass with the change. Checks: `scripts/lint.sh` clean, `uv run pytest` 2183 passed (plus `tests/integration/cross_version` 5 passed), coverage 93%. - [x] Follow the [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md). - [x] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification. - [x] Ensure the tests and linter pass - [x] Appropriate docs were updated (if necessary) Fixes a2aproject#1299 🦕 Co-authored-by: mykytanetipa <mykytanetipa@google.com>
1 parent 5a1a004 commit ee61dc1

4 files changed

Lines changed: 74 additions & 4 deletions

File tree

‎src/a2a/client/transports/rest.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,25 @@
4242

4343

4444
def _parse_rest_error(
45-
error_payload: dict[str, Any],
45+
error_payload: Any,
4646
fallback_message: str,
4747
) -> Exception | None:
4848
"""Parses a REST error payload and returns the appropriate A2AError.
4949
5050
Args:
51-
error_payload: The parsed JSON error payload.
51+
error_payload: The parsed JSON error payload. Any JSON value is
52+
accepted, since a proxy or gateway may answer with a body that
53+
is not a ``google.rpc.Status``.
5254
fallback_message: Message to use if the payload has no ``message``.
5355
5456
Returns:
5557
The mapped A2AError if a known reason was found, otherwise ``None``.
5658
"""
57-
error_data = error_payload.get('error', {})
59+
if not isinstance(error_payload, dict):
60+
return None
61+
error_data = error_payload.get('error')
62+
if not isinstance(error_data, dict):
63+
return None
5864
message = error_data.get('message', fallback_message)
5965
details = error_data.get('details', [])
6066
if not isinstance(details, list):

‎src/a2a/compat/v0_3/rest_transport.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,8 @@ def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn:
351351
error_data = e.response.json()
352352
except (json.JSONDecodeError, ValueError, httpx.ResponseNotRead):
353353
error_data = {}
354+
if not isinstance(error_data, dict):
355+
error_data = {}
354356

355357
error_type = error_data.get('type')
356358
message = error_data.get('message', str(e))

‎tests/client/transports/test_rest_client.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
TaskState,
2727
)
2828
from a2a.utils.constants import TransportProtocol
29-
from a2a.utils.errors import A2A_ERROR_MAPPING
29+
from a2a.utils.errors import A2A_ERROR_MAPPING, MethodNotFoundError
3030
from google.protobuf import json_format
3131
from google.protobuf.timestamp_pb2 import Timestamp
3232

@@ -152,6 +152,42 @@ async def test_rest_mapped_errors(
152152
with pytest.raises(error_cls):
153153
await client.send_message(request=params)
154154

155+
@pytest.mark.parametrize(
156+
('status_code', 'body', 'expected_error'),
157+
[
158+
(401, {'error': 'invalid_token'}, A2AClientError),
159+
(404, {'error': 'Not Found'}, MethodNotFoundError),
160+
(502, ['bad gateway'], A2AClientError),
161+
(500, 'Internal Server Error', A2AClientError),
162+
(503, None, A2AClientError),
163+
],
164+
)
165+
def test_rest_non_status_error_bodies(
166+
self,
167+
mock_httpx_client: AsyncMock,
168+
mock_agent_card: MagicMock,
169+
status_code,
170+
body,
171+
expected_error,
172+
):
173+
"""JSON error bodies that are not a google.rpc.Status (e.g. from a proxy) fall back to the HTTP status."""
174+
client = RestTransport(
175+
httpx_client=mock_httpx_client,
176+
agent_card=mock_agent_card,
177+
url='http://agent.example.com/api',
178+
)
179+
mock_response = MagicMock(spec=httpx.Response)
180+
mock_response.status_code = status_code
181+
mock_response.json.return_value = body
182+
error = httpx.HTTPStatusError(
183+
'Error',
184+
request=httpx.Request('GET', 'http://test.url'),
185+
response=mock_response,
186+
)
187+
188+
with pytest.raises(expected_error):
189+
client._handle_http_error(error)
190+
155191
@pytest.mark.asyncio
156192
async def test_send_message_with_timeout_context(
157193
self, mock_httpx_client: AsyncMock, mock_agent_card: MagicMock

‎tests/compat/v0_3/test_rest_transport.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,32 @@ def test_compat_rest_transport_handle_http_error_invalid_error_type(transport):
591591
transport._handle_http_error(error)
592592

593593

594+
@pytest.mark.parametrize(
595+
('status_code', 'body', 'expected_error'),
596+
[
597+
(401, 'invalid_token', A2AClientError),
598+
(404, ['Not Found'], MethodNotFoundError),
599+
(503, None, A2AClientError),
600+
],
601+
)
602+
def test_compat_rest_transport_handle_http_error_non_object_body(
603+
transport, status_code, body, expected_error
604+
):
605+
mock_response = MagicMock(spec=httpx.Response)
606+
mock_response.status_code = status_code
607+
mock_response.json.return_value = body
608+
609+
mock_request = MagicMock(spec=httpx.Request)
610+
mock_request.url = 'http://example.com'
611+
612+
error = httpx.HTTPStatusError(
613+
'Error', request=mock_request, response=mock_response
614+
)
615+
616+
with pytest.raises(expected_error):
617+
transport._handle_http_error(error)
618+
619+
594620
def test_compat_rest_transport_handle_http_error_unknown_error_type(transport):
595621
mock_response = MagicMock(spec=httpx.Response)
596622
mock_response.status_code = 500

0 commit comments

Comments
 (0)