【问题标题】:How to handle an error that is within an except block that returns?如何处理返回的异常块内的错误?
【发布时间】:2021-09-08 10:40:24
【问题描述】:

背景

我正在编写一个 AWS Lambda 函数,它使用 Boto3 开发工具包在 Python 中访问 AWS 服务。

上下文

我的主函数/lambda 处理程序发出 API 请求。我检查请求中的状态代码并根据响应代码引发自定义异常。除了我创建一条描述性消息以通过 SNS 发送电子邮件以通知我错误。

我尝试过的

我在custom python exceptions with error codes and error messages 上读到了这个帖子

我在nested excpetions 上阅读了这个帖子,但并不真正了解如何将其应用于我的情况。

我也在handling exceptions that occur within except clause 上阅读了这个帖子,但我不明白如何翻译。

问题

如果引发错误并返回正确的信息,我该如何处理 SNS 发送?

class Error(Exception):
    pass

class Error_401(Error):
    pass

class Error_403(Error):
    pass

class Error_404(Error):
    pass

class Error_500(Error):
    pass

# This syntax is most likely wrong, I just pasted it
# from link 1
class SNS_Send_Error(Error):
    def __init__(self, code):
        self.code = code
    def __str__(self):
        return repr(self.code)

def create_sns_client(arn,message):
    try:
        sns = boto3.client("sns")
        res = sns.publish(
            TargetArn=arn,
            Message=json.dumps({"default": json.dumps(message)}),
            MessageStructure="json"
        )
    except ClientError as e:
        code = e.reponse['ResponseMetadata']['HTTStatusCode']
        message = e.response['Error']['Code']
        print(message)
        raise SNS_Send_Error('SNS failed to send message. \
            Responed with error code: {}'.fomat(code),code)
    return res

def status_codes(arg):
    if arg == 401:
        raise Error_401
    elif arg == 403:
        raise Error_403
    elif arg == 404:
        raise Error_404
    elif arg == 500:
        raise Error_500

def lambda_handler(event, context):

    # Other Code ...

    # Request data from GH API
    try:
        res = request_gh_data(gh_secret, jobId)
        status = res.status_code
        gh_response = res.json()

        status_codes(status)

    except Error_401 as e:
        message = generate_error(gh_response['message'], context)
        create_sns_client(message)
        return {
            'statusCode': status,
            'body': message
        }
    except Error_403 as e:
        message = generate_error(gh_response['message'], context)
        create_sns_client(message)
        return {
            'statusCode': status,
            'body': message
        }
    except Error_404 as e:
        message = generate_error(gh_response['message'], context)
        create_sns_client(message)
        return {
            'statusCode': status,
            'body': message
        }
    except Error_500 as e:
        message = generate_error(gh_response['message'], context)
        create_sns_client(message)
        return {
            'statusCode': status,
            'body': message
        }
    except SNS_Send_Error as e:
        code = e.reponse['ResponseMetadata']['HTTStatusCode']
        message = e.response['Error']['Code']
        print(message)
        return {
            "statusCode": code,
            "body": message 
        }

    # Additional Code

    return {
        'statusCode': 200,
        'body': "Success!"
    }

我们可以看到,在每个 except 块中,我都会根据发生的错误类型发送消息。我应该如何以最“Pythonic”的方式处理消息发送错误。

【问题讨论】:

  • request_gh_data 使用requests 并返回requests.Response 对象吗?如果是这种情况,您可以使用 response.raise_for_status() 而不是创建自定义异常
  • @IainShelvington 这很棒。感谢您清理那部分代码。嵌套异常应该如何处理?
  • 您现在应该只有一个except 可以捕获requests.HTTPError?您可以在此处嵌套try/except 以捕获SNS_Send_Error
  • @IainShelvington 好的,我需要确认嵌套没问题。谢谢!我明天可以根据你的建议为这个线程写一个答案并标记你。或者你可以自己写,不接受。

标签: python exception boto3


【解决方案1】:

您可以使用except 而不指定异常类型来处理任何类型的Exception。然后您可以通过e.__class__ 了解异常的原因。

try:
    # code to be executed
except Exception as e:
    # you can give your message 
    # or do the task you want
    # based on the exception class
    print('exception raised: ', e.__class__)

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多