【问题标题】:How to catch `botocore.errorfactory.UserNotFoundException`?如何捕捉`botocore.errorfactory.UserNotFoundException`?
【发布时间】:2021-07-26 03:11:45
【问题描述】:

我正在使用AWS Cognito 制作OAuth 服务器。我现在正在创建异常处理程序以防万一使用不存在,但 requests 打算得到一个

ipdb> pk
'David'
ipdb> res = self.cognito_client.admin_get_user(
            UserPoolId=settings.AWS_USER_POOL_ID,
            Username=pk
        )
*** botocore.errorfactory.UserNotFoundException: An error occurred (UserNotFoundException) when calling the AdminGetUser operation: User does not exist.
Traceback (most recent call last):
  File "/Users/sarit/.pyenv/versions/futuready-titan/lib/python3.8/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/sarit/.pyenv/versions/futuready-titan/lib/python3.8/site-packages/botocore/client.py", line 626, in _make_api_call
    raise error_class(parsed_response, operation_name)
boto3==1.12.15            # via -r el.in
botocore==1.15.15         # via boto3, s3transfer
django==3.0.3
python3.8.1

我已经与botocore source codeUserNotFoundException核实过

问题:
我怎么能具体catch这个exception

【问题讨论】:

  • 你是刚刚创建了一个用户,还是老了?通常,激活亚马逊帐户需要大约 1 天时间。
  • try 已经做什么了? (双关语:p)
  • @wovano 我试过BotoCoreError,但它不起作用

标签: python boto3 botocore


【解决方案1】:

botocore.error_factory创建异常时,不能直接导入。您应该使用生成的类来处理异常,而不是直接导入。

文档中为每个操作提供了可能的异常列表。例如,对于CognitoIdentityProvider.Client.admin_get_user,可能的例外是:

CognitoIdentityProvider.Client.exceptions.ResourceNotFoundException
CognitoIdentityProvider.Client.exceptions.InvalidParameterException
CognitoIdentityProvider.Client.exceptions.TooManyRequestsException
CognitoIdentityProvider.Client.exceptions.NotAuthorizedException
CognitoIdentityProvider.Client.exceptions.UserNotFoundException
CognitoIdentityProvider.Client.exceptions.InternalErrorException

有一个示例说明如何获取客户端的示例列表以及如何处理它(当然异常列表取决于操作):

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))

此外,您可能会看到输入较少的 botocore.exceptions.ClientError 而不是特定的:

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))

【讨论】:

    【解决方案2】:

    有两种方法,如果异常暴露在客户端,您可以直接捕获它,或者从 botocore.exceptions 导入并使用它。

    选项 1:

    try: 
        res = self.cognito_client.admin_get_user(
                  UserPoolId=settings.AWS_USER_POOL_ID,
                  Username=pk
              )
    except self.cognito_client.exceptions.UserNotFoundException as e:
        print(e)
    

    选项 2:

    from botocore.exceptions import UserNotFoundException
    
    try: 
        res = self.cognito_client.admin_get_user(
                  UserPoolId=settings.AWS_USER_POOL_ID,
                  Username=pk
              )
    except UserNotFoundException as e:
        print(e)
    

    有关更多详细信息,请参阅 boto 错误处理documentation

    【讨论】:

    • 无法从“botocore.exceptions”(/home/ec2-user/anaconda3/envs/python38/lib/python3.8/site-packages/botocore/exceptions.py)导入名称“UserNotFoundException”
    • 这不起作用。正如@NicWanavit 所说,导入行会引发错误。
    【解决方案3】:

    这当然不是理想的,但我能够抓住它:

    from botocore.exceptions import ClientError
    
    try:
        func_that_interacts_with_cognito()
    except ClientError:
        # This happens when the user is not found.
        print("It happened again ...")
    

    【讨论】:

    • 这实际上对我有用,因为我需要捕获由 botocore.error_factory 创建的 NotAuthorizedException
    猜你喜欢
    • 2011-12-30
    • 1970-01-01
    • 2018-10-30
    • 2017-07-15
    • 1970-01-01
    • 2012-03-20
    • 2020-01-27
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多