From 7ea92e6d4e5c332df9d2f8666c5f8d3c07c45f71 Mon Sep 17 00:00:00 2001 From: Hallie Lomax Date: Mon, 8 Jul 2019 11:50:03 -0700 Subject: [PATCH] helper functions to get error code and message from response (#658) --- .gitignore | 1 + pynamodb/exceptions.py | 8 ++++++++ pynamodb/exceptions.pyi | 4 ++++ tests/test_exceptions.py | 42 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 tests/test_exceptions.py diff --git a/.gitignore b/.gitignore index f0a6a7381..040eb66d5 100644 --- a/.gitignore +++ b/.gitignore @@ -60,6 +60,7 @@ cover/ # PyCharm .idea/ +build/ # Ignore Cache .cache/ diff --git a/pynamodb/exceptions.py b/pynamodb/exceptions.py index 68e1c8e9f..aa0a5ed7e 100644 --- a/pynamodb/exceptions.py +++ b/pynamodb/exceptions.py @@ -14,6 +14,14 @@ def __init__(self, msg=None, cause=None): self.cause = cause super(PynamoDBException, self).__init__(self.msg) + @property + def cause_response_code(self): + return getattr(self.cause, 'response', {}).get('Error', {}).get('Code') + + @property + def cause_response_message(self): + return getattr(self.cause, 'response', {}).get('Error', {}).get('Message') + class PynamoDBConnectionError(PynamoDBException): """ diff --git a/pynamodb/exceptions.pyi b/pynamodb/exceptions.pyi index 728db4a7b..3b1df2e6e 100644 --- a/pynamodb/exceptions.pyi +++ b/pynamodb/exceptions.pyi @@ -4,6 +4,10 @@ class PynamoDBException(Exception): msg: str cause: Any def __init__(self, msg: Optional[Text] = ..., cause: Optional[Exception] = ...) -> None: ... + @property + def cause_response_code(self) -> Optional[str]: ... + @property + def cause_response_message(self) -> Optional[str]: ... class PynamoDBConnectionError(PynamoDBException): ... class DeleteError(PynamoDBConnectionError): ... diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py new file mode 100644 index 000000000..48698f1f4 --- /dev/null +++ b/tests/test_exceptions.py @@ -0,0 +1,42 @@ +from botocore.exceptions import ClientError + +from pynamodb.exceptions import PutError + + +def test_get_cause_response_code(): + error = PutError( + cause=ClientError( + error_response={ + 'Error': { + 'Code': 'hello' + } + }, + operation_name='test' + ) + ) + assert error.cause_response_code == 'hello' + + +def test_get_cause_response_code__no_code(): + error = PutError() + assert error.cause_response_code is None + + +def test_get_cause_response_message(): + error = PutError( + cause=ClientError( + error_response={ + 'Error': { + 'Message': 'hiya' + } + }, + operation_name='test' + ) + ) + assert error.cause_response_message == 'hiya' + + +def test_get_cause_response_message__no_message(): + error = PutError() + assert error.cause_response_message is None +