catching exceptions from boto3

0

I'm coding a script to upload data to s3 and I'm wondering how I know what exceptions to catch. I've seen the documentation here (https://boto3.amazonaws.com/v1/documentation/api/latest/guide/error-handling.html), but now I'm getting an botocore.exceptions.EndpointConnectionError. How do I know I am catching all the exceptions for boto3 that I need to catch? Please don't tell me it's trial and error.

已提問 2 年前檢視次數 5256 次
2 個答案
1
已接受的答案

The S3 API guide provides all possible error responses thrown by the S3 service. Additionally, the Python package aws-error-utils can streamline some of the error handling in boto3.

lurch
已回答 2 年前
  • Thanks. I'll try and reproduce the problem with that aws_error_utils package being used. I'll see if that helps. Thanks.

1

You could try to catch ClientError and then parse the error response, for example,

import boto3, botocore.exceptions

s3 = boto3.client('s3')
try:
    s3.get_object(Bucket='some-bucket', Key='some key')
except botocore.exceptions.ClientError as error:
    if error.response['Error']['Code'] == 'NoSuchKey':
        print('No such object')
    else: # Unknown exception
        print(error.response)
RoB
已回答 2 年前
  • Oh. Would that ClientError under botocore.exceptions catch a EndpointConnectionError? This job runs for a day or two so it takes a while to reproduce.

  • @jschwar313 You can generate a list of the statically defined botocore exceptions using the following code (taken from boto3 docs

    import botocore.exceptions
    
    for key, value in sorted(botocore.exceptions.__dict__.items()):
        if isinstance(value, type):
            print(key)
    

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南