25

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?

helloV
  • 50,176
  • 7
  • 137
  • 145
zalpha314
  • 1,444
  • 4
  • 19
  • 34

2 Answers2

34
mc = boto3.client('ssm')
try:
  ...
except mc.exceptions.ParameterNotFound:
  ...
wscourge
  • 10,657
  • 14
  • 59
  • 80
gladiatr72
  • 441
  • 4
  • 2
  • 1
    When I try this and it reaches the `except` line it generates an exception stating `exceptions must derive from the base class` so I question if this is really valid – Shawn Jul 30 '19 at 23:58
20

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'])
charlax
  • 25,125
  • 19
  • 60
  • 71
helloV
  • 50,176
  • 7
  • 137
  • 145
  • 9
    This isn't difficult to understand from a code perspective. What's difficult to understand from a design perspective is that you can't directly import or name an error from its callstack name in boto3. Neither `import botocore.errorfactory.ResourceNotFoundException` or `except botocore.errorfactory.ResourceNotFoundException` work. But both are what one would immediately want to try after receiving said error. Puzzling. – fIwJlxSzApHEZIl Sep 10 '18 at 13:28
  • 1
    Also see this answer for more info about the structure of the ClientError response: https://stackoverflow.com/a/33663484 – charlesreid1 Aug 27 '19 at 16:08