From 93ef9634e77f3f92e384f9568c88d9828818a15b Mon Sep 17 00:00:00 2001 From: Ofer Koren Date: Wed, 25 Oct 2023 22:01:40 +0300 Subject: [PATCH] Raise appropriate exceptions for condition failures (#1076) --- pynamodb/connection/base.py | 10 ++++++++-- pynamodb/exceptions.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/pynamodb/connection/base.py b/pynamodb/connection/base.py index 975b02e8..e5a14200 100644 --- a/pynamodb/connection/base.py +++ b/pynamodb/connection/base.py @@ -1048,7 +1048,10 @@ def update_item( try: return self.dispatch(UPDATE_ITEM, operation_kwargs, settings) except BOTOCORE_EXCEPTIONS as e: - raise UpdateError("Failed to update item: {}".format(e), e) + exc = UpdateError("Failed to update item: {}".format(e), e) + if exc.cause_response_code == "ConditionalCheckFailedException": + exc.__class__ = ConditionFailedUpdate + raise exc def put_item( self, @@ -1079,7 +1082,10 @@ def put_item( try: return self.dispatch(PUT_ITEM, operation_kwargs, settings) except BOTOCORE_EXCEPTIONS as e: - raise PutError("Failed to put item: {}".format(e), e) + exc = PutError("Failed to put item: {}".format(e), e) + if exc.cause_response_code == "ConditionalCheckFailedException": + exc.__class__ = ConditionFailedPut + raise exc def _get_transact_operation_kwargs( self, diff --git a/pynamodb/exceptions.py b/pynamodb/exceptions.py index 39dd5437..c252f3ad 100644 --- a/pynamodb/exceptions.py +++ b/pynamodb/exceptions.py @@ -84,6 +84,13 @@ class PutError(PynamoDBConnectionError): msg = "Error putting item" +class ConditionFailedPut(PutError): + """ + Raised when an item fails to be created due to condition + """ + msg = "Condition failed while putting item" + + class UpdateError(PynamoDBConnectionError): """ Raised when an item fails to be updated @@ -91,6 +98,13 @@ class UpdateError(PynamoDBConnectionError): msg = "Error updating item" +class ConditionFailedUpdate(UpdateError): + """ + Raised when an item fails to be updated due to condition + """ + msg = "Condition failed while updating item" + + class GetError(PynamoDBConnectionError): """ Raised when an item fails to be retrieved