Anyone that works with DynamoDB is probably familiar with the ConditionalCheckFailed Exception. This error occurs when a condition placed on your api request fails to be satisfied.
Take for example a PutItem request on an Orders table to insert a new record. When using this API, it’s wise to use a ConditionExpression with the value attribute_not_exists. This ensures that if a record is already present with the same key, a ConditionalCheckFailed exception gets thrown. Receiving an exception indicates a problem occurred, but it doesn’t provide you additional context about the item that existed in the table.
But now, a new few feature allows you to receive a copy of the item in the database as it existed when the conditional error is encountered. This is helpful across a broad range of applications including debugging, enhanced logging, and pretty much any other use case that benefits from read after write flows during exception handling.
How ReturnValuesOnConditionCheckFailure Works
How this feature works is pretty simple.
Let’s take a basic PutItem example in Python. This is how our code would look normally without this new feature. We’re doing a simple put_item call and providing our Table name, item, and Condition expression. Notice that if an error does get thrown, all we get back is a simple response code and not much else.
With the change applied, our code looks similar but has a few additions. Notice here we’re adding the ReturnValuesOnConditionCheckFailure field with a value of ALL_OLD. This is telling Dynamo that if a Conditional error is encountered, to also return the item in the database as part of the response.
With this, we can also do some more interesting things with error handling. Instead of just logging a simple response code, we can check for the error type, and if it’s present, log out the item from the response. This is super easy to use and can add lots of value.
This example was showing put item, but the feature is also supported by for update item and delete item api’s as well.
And one more thing… this feature is absolutely free to use! You’re not charged at all for requesting the value or receiving it – so really, there’s no reason to not start using it right now.
To learn more about Conditions and this new feature, go here. And to learn more about ReturnValuesOnConditionCheckFailure , check out AWS blog post announcement here.