Boto3 AWS API error responses for SSM

早过忘川 提交于 2019-12-08 03:50:35

问题


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:

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.

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.


回答1:


You can try catching 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:


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 = 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


来源:https://stackoverflow.com/questions/48955999/boto3-aws-api-error-responses-for-ssm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!