fix(api-core): handle list-shaped REST error payloads - #18232
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the format_http_response_error function in exceptions.py to handle cases where the HTTP response payload is a list, extracting the first dictionary item from the list to parse the error. It also adds corresponding unit tests. The reviewer suggested ensuring that payload is explicitly validated as a dictionary to prevent potential AttributeError crashes if the payload is of another non-dictionary type, which aligns with defensive programming guidelines.
| if isinstance(payload, list): | ||
| payload = next((item for item in payload if isinstance(item, dict)), {}) | ||
| payload = {} if not payload else payload |
There was a problem hiding this comment.
To ensure robust defensive programming against untrusted or malformed REST payloads, we should guarantee that payload is a dictionary before calling .get() on it. If the payload is a string, number, or other non-dictionary type, the current implementation will raise an AttributeError. Replacing the falsy check with an explicit isinstance(payload, dict) check prevents potential crashes.
| if isinstance(payload, list): | |
| payload = next((item for item in payload if isinstance(item, dict)), {}) | |
| payload = {} if not payload else payload | |
| if isinstance(payload, list): | |
| payload = next((item for item in payload if isinstance(item, dict)), {}) | |
| if not isinstance(payload, dict): | |
| payload = {} |
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:
Fixes #18223 🦕
Summary
errorobject.unknown errorwhen no dict item is present.Tests
pytest -q tests/unit/test_exceptions.py -k 'http_response or error_details_from_rest_response'pytest -q tests/unit/test_exceptions.pyruff format --check --target-version=py310 --line-length=88 google/api_core/exceptions.py tests/unit/test_exceptions.pyflake8 google/api_core/exceptions.py tests/unit/test_exceptions.pygit diff --checkCLA
Google CLA is required by the repository; awaiting the repository's CLA check on this PR.