Skip to content

Commit

Permalink
Add ClientError getters for code, message, http_headers, http_status_…
Browse files Browse the repository at this point in the history
…code, and request_id

This change adds the following properties to the ClientError class. These properties will make it easier to
work with the error object and extract information from it.

- code: The error code returned by the service.
- message: The error message returned by the service.
- http_headers: The HTTP headers returned by the service.
- http_status_code: The HTTP status code returned by the service.
- request_id: The request ID returned by the service.
  • Loading branch information
m-mortimer committed Sep 11, 2024
1 parent 1fd6e69 commit c68b5d1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
25 changes: 25 additions & 0 deletions botocore/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,31 @@ def __reduce__(self):
# module. So at the very least return a ClientError back.
return ClientError, (self.response, self.operation_name)

@property
def code(self):
"""The error code returned by the AWS service."""
return self.response.get('Error', {}).get('Code', 'Unknown')

@property
def message(self):
"""The error message returned by the AWS service."""
return self.response.get('Error', {}).get('Message', 'Unknown')

@property
def request_id(self):
"""The request ID returned by the AWS service."""
return self.response.get('ResponseMetadata').get('RequestId')

@property
def http_status_code(self):
"""The HTTP status code returned by the AWS service."""
return self.response.get('ResponseMetadata', {}).get('HTTPStatusCode')

@property
def http_headers(self):
"""The HTTP headers returned by the AWS service."""
return self.response.get('ResponseMetadata', {}).get('HTTPHeaders', {})


class EventStreamError(ClientError):
pass
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ def test_client_error_can_handle_missing_code_or_message():
response = {'Error': {}}
expect = 'An error occurred (Unknown) when calling the blackhole operation: Unknown'
assert str(exceptions.ClientError(response, 'blackhole')) == expect
assert exceptions.ClientError.code == 'Unknown'
assert exceptions.ClientError.message == 'Unknown'


def test_client_error_can_handle_missing_response_metadata():
response = {'Error': {}}
assert (
exceptions.ClientError(response, 'blackhole').http_status_code is None
)
assert exceptions.ClientError(response, 'blackhole').request_id is None
assert exceptions.ClientError(response, 'blackhole').http_headers == {}


def test_client_error_has_operation_name_set():
Expand Down

0 comments on commit c68b5d1

Please sign in to comment.