【发布时间】: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 好的,我需要确认嵌套没问题。谢谢!我明天可以根据你的建议为这个线程写一个答案并标记你。或者你可以自己写,不接受。