How can I import the boto3 ssm ParameterNotFound e

2020-07-02 08:40发布

问题:

I would like to import the exception that occurs when a boto3 ssm parameter is not found with get_parameter. I'm trying to add some extra ssm functionality to the moto library, but I am stumped at this point.

>>> import boto3
>>> ssm = boto3.client('ssm')
>>> try:
        ssm.get_parameter(Name='not_found')
    except Exception as e:
        print(type(e))
<class 'botocore.errorfactory.ParameterNotFound'>
>>> from botocore.errorfactory import ParameterNotFound
ImportError: cannot import name 'ParameterNotFound'
>>> import botocore.errorfactory.ParameterNotFound
ModuleNotFoundError: No module named 'botocore.errorfactory.ParameterNotFound'; 'botocore.errorfactory' is not a package

However, the Exception cannot be imported, and does not appear to exist in the botocore code. How can I import this exception?

回答1:

From Botocore Error Handling

import boto3
from botocore.exceptions import ClientError

ssm = boto3.client('ssm')
try:
    ssm.get_parameter(Name='not_found')
except ClientError as e:
    print e.response['Error']['Code']


回答2:

mc = boto3.client('ssm')
try:
  ...
except mc.exceptions.ParameterNotFound:
  ...