27

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?

3 Answers 3

38
mc = boto3.client('ssm') try: ... except mc.exceptions.ParameterNotFound: ... 
Sign up to request clarification or add additional context in comments.

1 Comment

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
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']) 

2 Comments

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.
Also see this answer for more info about the structure of the ClientError response: stackoverflow.com/a/33663484
1

Below is a wrapper function so that you have a pythonic Exception

import boto3 from botocore.exceptions import ClientError class ParameterNotFound(Exception): pass def get_parameter(ssm, *args, **kwargs): try: return ssm.get_parameter(*args, **kwargs) except ClientError as exc: if exc.response['Error']['Code'] == 'ParameterNotFound': raise ParameterNotFound from exc raise get_parameter(boto3.client('ssm'), Name='/my/param') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.