问题描述
我想弄清楚如何使用 boto3 进行正确的错误处理.
I am trying to figure how to do proper error handling with boto3.
我正在尝试创建 IAM 用户:
I am trying to create an IAM user:
def create_user(username, iam_conn):
try:
user = iam_conn.create_user(UserName=username)
return user
except Exception as e:
return e
当调用 create_user 成功时,我得到一个整洁的对象,其中包含 API 调用的 http 状态代码和新创建用户的数据.
When the call to create_user succeeds, I get a neat object that contains the http status code of the API call and the data of the newly created user.
示例:
{'ResponseMetadata':
{'HTTPStatusCode': 200,
'RequestId': 'omitted'
},
u'User': {u'Arn': 'arn:aws:iam::omitted:user/omitted',
u'CreateDate': datetime.datetime(2015, 10, 11, 17, 13, 5, 882000, tzinfo=tzutc()),
u'Path': '/',
u'UserId': 'omitted',
u'UserName': 'omitted'
}
}
这很好用.但是当这失败时(比如如果用户已经存在),我只会得到一个 botocore.exceptions.ClientError 类型的对象,只有文本告诉我出了什么问题.
This works great. But when this fails (like if the user already exists), I just get an object of type botocore.exceptions.ClientError with only text to tell me what went wrong.
示例:ClientError('调用 CreateUser 操作时发生错误 (EntityAlreadyExists): 名称省略的用户已经存在.',)
Example:ClientError('An error occurred (EntityAlreadyExists) when calling the CreateUser operation: User with name omitted already exists.',)
这 (AFAIK) 使错误处理变得非常困难,因为我不能只打开结果 http 状态代码(根据 IAM 的 AWS API 文档,用户的 409 已经存在).这让我觉得我一定是在以错误的方式做某事.最佳方式是 boto3 从不抛出异常,但 juts 始终返回一个反映 API 调用方式的对象.
This (AFAIK) makes error handling very hard because I can't just switch on the resulting http status code (409 for user already exists according to the AWS API docs for IAM). This makes me think that I must be doing something the wrong way. The optimal way would be for boto3 to never throw exceptions, but juts always return an object that reflects how the API call went.
谁能在这个问题上启发我或为我指明正确的方向?
Can anyone enlighten me on this issue or point me in the right direction?
推荐答案
使用包含在异常中的响应.下面是一个例子:
Use the response contained within the exception. Here is an example:
import boto3
from botocore.exceptions import ClientError
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
print("User already exists")
else:
print("Unexpected error: %s" % e)
异常中的响应字典将包含以下内容:
The response dict in the exception will contain the following:
['Error']['Code']
例如'EntityAlreadyExists' 或 'ValidationError'['ResponseMetadata']['HTTPStatusCode']
例如400['ResponseMetadata']['RequestId']
例如'd2b06652-88d7-11e5-99d0-812348583a35'['Error']['Message']
例如发生错误(EntityAlreadyExists)..."['Error']['Type']
例如'发件人'
['Error']['Code']
e.g. 'EntityAlreadyExists' or 'ValidationError'['ResponseMetadata']['HTTPStatusCode']
e.g. 400['ResponseMetadata']['RequestId']
e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'['Error']['Message']
e.g. "An error occurred (EntityAlreadyExists) ..."['Error']['Type']
e.g. 'Sender'
有关更多信息,请参阅:
For more information see:
[更新时间:2018-03-07]
AWS Python SDK 已开始在客户端上公开服务异常(虽然不是在 resources 上),您可以明确捕获,所以现在可以像这样编写代码:
The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:
import botocore
import boto3
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
print("User already exists")
except botocore.exceptions.ParamValidationError as e:
print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
print("Unexpected error: %s" % e)
遗憾的是,目前没有关于这些错误/异常的文档,但您可以获得核心错误列表,如下所示:
Unfortunately, there is currently no documentation for these errors/exceptions but you can get a list of the core errors as follows:
import botocore
import boto3
[e for e in dir(botocore.exceptions) if e.endswith('Error')]
请注意,您必须同时导入 botocore 和 boto3.如果你只导入 botocore 那么你会发现 botocore 没有名为 exceptions
的属性.这是因为异常是由 boto3 动态填充到 botocore 中的.
Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions
. This is because the exceptions are dynamically populated into botocore by boto3.
您可以按如下方式获取特定于服务的异常列表(根据需要将iam
替换为相关服务):
You can get a list of service-specific exceptions as follows (replace iam
with the relevant service as needed):
import boto3
iam = boto3.client('iam')
[e for e in dir(iam.exceptions) if e.endswith('Exception')]
[更新时间:2021-09-07]
除了前面提到的客户端异常方法,还有一个名为aws的第三方辅助包-error-utils.
In addition to the aforementioned client exception method, there is also a third-party helper package named aws-error-utils.
这篇关于如何处理 boto3 的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!