从boto3捕获异常。

0

【以下的问题经过翻译处理】 我正在编写一个脚本来上传数据到s3,想知道我该捕获哪些异常。我看过这篇文档(https://boto3.amazonaws.com/v1/documentation/api/latest/guide/error-handling.html),但现在我得到了botocore.exceptions.EndpointConnectionError。我怎么知道我捕获了我需要捕获的所有boto3异常?

profile picture
EXPERTE
gefragt vor 6 Monaten10 Aufrufe
2 Antworten
0

【以下的回答经过翻译处理】 S3 API指南提供了S3服务可能抛出的所有错误响应。此外,Python包aws-error-utils可以简化boto3中的一些错误处理。

profile picture
EXPERTE
beantwortet vor 6 Monaten
0

您好,

针对boto3的错误处理,可以参考以下来源。

boto3 特定API的文档:
在boto3的官方文档中,每项API里可能有此API相关的错误类别的纪录,通常相关资讯会纪录于Exception的段落中。像是s3.client的get_object的官方文档[1],最下面则列出了S3.Client.exceptions.NoSuchKey与S3.Client.exceptions.InvalidObjectState两项错误类别。

botocore内的错误类别:
套件botocore中有多数关于boto3 API的错误类别,像是一般的权限错误等类别。您可以透过以下程式码列出所有的错误类别

import boto3
import botocore
print([i for i in dir(botocore.exceptions) if 'error' in i.lower()])

若您要针对botocore特定错误做处理,如您举的例子,则可以直接带入,如下方程式码:

import boto3
import botocore
try:
    # code
except botocore.exceptions.EndpointConnectionError as e:
    # error handling

[1] https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html

AWS
Ling_L
beantwortet vor 6 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen