When an exception is created by botocore.error_factory
then it is not possible to directly import it. Instead of direct import, you should use generated classes for exceptions.
A list of possible exceptions is provided for each operation in the documentation. For example, for CognitoIdentityProvider.Client.admin_get_user, possible exceptions are:
CognitoIdentityProvider.Client.exceptions.ResourceNotFoundException
CognitoIdentityProvider.Client.exceptions.InvalidParameterException
CognitoIdentityProvider.Client.exceptions.TooManyRequestsException
CognitoIdentityProvider.Client.exceptions.NotAuthorizedException
CognitoIdentityProvider.Client.exceptions.UserNotFoundException
CognitoIdentityProvider.Client.exceptions.InternalErrorException
There is an example of how to get the list of examples for a client and how to handle it (of course list of exceptions is depend from operation):
import boto3
eks = boto3.client('eks')
print(dir(eks.exceptions))
# ['BadRequestException',
# 'ClientError',
# 'ClientException',
# 'InvalidParameterException',
# 'InvalidRequestException',
# 'NotFoundException',
# 'ResourceInUseException',
# 'ResourceLimitExceededException',
# 'ResourceNotFoundException',
# 'ServerException',
# 'ServiceUnavailableException',
# 'UnsupportedAvailabilityZoneException', ...]
try:
response = eks.list_nodegroups(clusterName='my-cluster')
except eks.exceptions.ResourceNotFoundException as e:
# do something with e
print("handled: " + str(e))
cognito_idp = boto3.client('cognito-idp')
print(dir(cognito_idp.exceptions))
# [ 'ClientError',
# 'ConcurrentModificationException',
# 'DeveloperUserAlreadyRegisteredException',
# 'ExternalServiceException',
# 'InternalErrorException',
# 'InvalidIdentityPoolConfigurationException',
# 'InvalidParameterException',
# 'LimitExceededException',
# 'NotAuthorizedException',
# 'ResourceConflictException',
# 'ResourceNotFoundException',
# 'TooManyRequestsException', ... ]
try:
response = cognito_idp.admin_get_user(
UserPoolId='pool_id',
Username='username'
)
except cognito_idp.exceptions.UserNotFoundException as e:
# do something with e
print("handled: " + str(e))
Additionally, you may catch the less typed botocore.exceptions.ClientError
instead of specific ones:
import boto3
import botocore.exceptions
try:
response = cognito_idp.admin_get_user(
UserPoolId='pool_id',
Username='username'
)
except botocore.exceptions.ClientError as e:
# do something with e
print("handled: " + str(e))
try
already? (pun intended :p) – DisyllableBotoCoreError
, but it is not work – Unattended