How to handle errors with boto3?

后端 未结 10 887
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:02

I am trying to figure how to do proper error handling with boto3.

I am trying to create an IAM user:

def create_user(username, iam_conn):
    try:
           


        
10条回答
  •  鱼传尺愫
    2020-12-02 04:43

    In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

    try:
        ### Boto3 client code here...
    
    except boto_exceptions.ClientError as error:
        Log.warning("Catched client error code %s",
                    error.response['Error']['Code'])
    
        if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                               "InvalidSequenceTokenException"]:
            Log.debug(
                "Fetching sequence_token from boto error response['Error']['Message'] %s",
                error.response["Error"]["Message"])
            # NOTE: apparently there's no sequenceToken attribute in the response so we have
            # to parse response["Error"]["Message"] string
            sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
            Log.debug("Setting sequence_token to %s", sequence_token)
    

    This works both at first attempt (with empty LogStream) and subsequent ones.

提交回复
热议问题