如何捕获 DynamoDB ResourceInUseException Python?

How to catch DynamoDB ResourceInUseException Python?

所以这是个例外:

botocore.errorfactory.ResourceInUseException: An error occurred (ResourceInUseException) when calling the CreateTable operation: Cannot create preexisting table

我正在阅读他们的教程,并搜索了一些 Python 和 Dynamodb 例外,但到目前为止还没有运气。 我只看到 ClientError 异常,但没有看到这个特定的异常。

https://docs.aws.amazon.com/search/doc-search.html?searchPath=documentation&searchQuery=python%20dynamodb%20exceptions

我尝试了几种变体,例如:

except boto3.ResourceInUseException:
except botocore.errorfactory.ResourceInUseException

各种其他,但不存在此类例外。

我不确定捕获异常的正确方法是什么(当 table 已经存在时)。

谢谢。

捕获任何异常的一种通用方法是捕获 Exception 然后比较名称。例如:

try:
    try:
        #implementation
    except Exception as e:
        if e.__class__.__name__ == 'ResourceInUseException':
             #handle exception
        else:
             raise e

except Exception as e:
    #handle other exceptions except ResourceInUseException exception

另一种选择是,您可以尝试从库中导入异常。例如:

from botocore.errorfactory import ResourceInUseException # or something similar

尽管我不确定 ResourceInUseException 存在于哪个模块中,但您可以尝试各种选项。

你可以参考这个,它处理了类似的情况。

如您所见,boto3 对从服务器接收到的所有错误抛出相同的异常类型 ClientError。在其他情况下它可能会抛出其他异常(例如 boto3 在将请求发送到服务器之前发现请求错误,或者当它无法连接到服务器时) - 但 DynamoDB 本身的所有错误 returns 组合成 ClientError.

您可以解析此异常的字符串内容以查看它是否包含 ResourceInUseException。

boto3 documentation 包含对此的(不是很清楚)解释和示例:

try:
    logger.info('Calling DescribeStream API on myDataStream')
    client.describe_stream(StreamName='myDataStream')

except botocore.exceptions.ClientError as error:
    if error.response['Error']['Code'] == 'LimitExceededException':
        logger.warn('API call limit exceeded; backing off and retrying...')
    else:
        raise error

并且还注意到有一个更好的替代方案,您可能更喜欢在“客户端”对象中使用异常的动态映射:

except client.meta.client.exceptions.BucketAlreadyExists as err:
    print("Bucket {} already exists!".format(err.response['Error']['BucketName']))
    raise err