阅读背景:

Boto3 AWS SSM API错误响应

来源:互联网 

I am using a simple boto3 script to retrieve a parameter from SSM param store in my aws account. The python script looks like below:

我使用一个简单的boto3脚本从aws帐户中从SSM param存储中检索参数。python脚本如下所示:

client = get_boto3_client('ssm', 'us-east-1')
try:
    response = client.get_parameter(Name='my_param_name',WithDecryption=True)
except Exception as e:
    logging.error("retrieve param error: {0}".format(e))
    raise e
return response

If the given parameter is not available, I get a generic error in the response like below:

如果给定的参数不可用,则在响应中出现如下所示的一般错误:

 An error occurred (ParameterNotFound) when calling the GetParameter operation: Parameter my_param_name not found.   

I have verified method signature from boto3 ssm docs. Related AWS API Docs confirms to return a 400 response when parameter does not exist in the param store.

我已经从boto3 ssm文档中验证了方法签名。当参数在param存储中不存在时,AWS API文档确认返回400个响应。

My question is that how do I verify if the exception caught in the response is actually a 400 status code so that I can handle it accordingly.

我的问题是,如何验证响应中捕获的异常是否实际上是一个400状态码,以便我能够相应地处理它。

2 个解决方案

#1


2  

You can try catching client.exceptions.ParameterNotFound:

您可以尝试捕获client.exceptions.ParameterNotFound:

client = get_boto3_client('ssm', 'us-east-1')

try:
  response = client.get_parameter(Name='my_param_name',WithDecryption=True)
except client.exceptions.ParameterNotFound:
  logging.error("not found")

#2


0  

You can look at the status via response['Error']['Code'], but since there are multiple reasons for a 400, I would recommend a better approach:

你可以通过response['Error']['Code']来查看状态,但是由于400个原因很多,我推荐一个更好的方法:

response = client.get_parameter(Name='my_param_name',WithDecryption=True)

if 'Parameters' not in response:
    raise ValueError('Response did not contain parameters key')
else:
    return response

分享到: