2

So this is the exception:

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

I am going through their tutorials, and have searched for some code examples of Python and Dynamodb exceptions but so far no luck. I only see ClientError exception, but not this specific one.

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

I have tried several variants such as :

except boto3.ResourceInUseException:
except botocore.errorfactory.ResourceInUseException

various others, but no such exception exists.

I am not sure what the proper way to catch such as exception (when a table already exists).

Thank you.

MasayoMusic
  • 594
  • 1
  • 6
  • 24

2 Answers2

3

As you noticed, boto3 throws the same exception type, ClientError, on all errors that were received from the server. There are other exception it can throw in other occasions (such as boto3 found an error in the request before even sending it to the server, or when it can't connect to the server) - but all errors that DynamoDB itself returns are bunched together as a ClientError.

You can parse this exception's string content to see if it contains a ResourceInUseException or not.

The boto3 documentation contains a (not very clear) explanation of this, and an example:

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

and also notes that there is a nicer alternative which you may prefer, using a dynamic map of exceptions in the "client" object:

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

Nadav Har'El
  • 11,785
  • 1
  • 24
  • 45
0

One general way to catch any exception would be to catch Exception and then compare the name. For eg:

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

Another option is that, you can try importing the exception from the library. For eg:

from botocore.errorfactory import ResourceInUseException # or something similar

Although, I'm not sure in which module ResourceInUseException exists, but you can try out various options.

You can refer this answer, which deals with a similar situation.

mtm
  • 504
  • 1
  • 7
  • 25