Skip to content

Surface caused_by in ApiError #2932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions elasticsearch/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,15 @@ def __str__(self) -> str:
if self.body and isinstance(self.body, dict) and "error" in self.body:
if isinstance(self.body["error"], dict):
root_cause = self.body["error"]["root_cause"][0]
caused_by = self.body["error"].get("caused_by", {})
cause = ", ".join(
filter(
None,
[
repr(root_cause["reason"]),
root_cause.get("resource.id"),
root_cause.get("resource.type"),
caused_by.get("reason"),
],
)
)
Expand Down
30 changes: 30 additions & 0 deletions test_elasticsearch/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,33 @@ def test_transform_error_parse_with_error_string(self):
assert (
str(e) == "ApiError(500, 'InternalServerError', 'something error message')"
)

def test_transform_invalid_media_type_error(self):
e = ApiError(
message="InvalidMediaType",
meta=error_meta,
body={
"error": {
"root_cause": [
{
"type": "media_type_header_exception",
"reason": "Invalid media-type value on headers [Accept, Content-Type]",
}
],
"type": "media_type_header_exception",
"reason": "Invalid media-type value on headers [Accept, Content-Type]",
"caused_by": {
"type": "status_exception",
"reason": "Accept version must be either version 8 or 7, but found 9. Accept=application/vnd.elasticsearch+json; compatible-with=9",
},
},
"status": 400,
},
)

assert str(e) == (
"ApiError(500, 'InvalidMediaType', "
"'Invalid media-type value on headers [Accept, Content-Type]', "
"Accept version must be either version 8 or 7, but found 9. "
"Accept=application/vnd.elasticsearch+json; compatible-with=9)"
)
Loading