Skip to content

Instantly share code, notes, and snippets.

@skeggse
Last active March 21, 2024 06:39
Show Gist options
  • Save skeggse/511088dcc6b3f744548bcbd2e8e7c91b to your computer and use it in GitHub Desktop.
Save skeggse/511088dcc6b3f744548bcbd2e8e7c91b to your computer and use it in GitHub Desktop.
No boto3.client handy? Need to catch a boto3 exception? Build the exceptions via two obscure methods!
from typing import Optional
from boto3 import Session
from botocore import UNSIGNED
from botocore.config import Config
from mypy_boto3_servicecatalog.literals import ServiceName
def build_service_exceptions(
service_name: ServiceName, *, session: Optional[Session] = None
):
"""
Build a ClientExceptions for the given service name.
"""
if not session:
session = Session()
return session.client(
service_name,
# Skip the normal credential provider chain by telling the client to
# use unsigned requests. Without this, the client will attempt to
# use the default credential provider chain, which results in a
# process of trying to connect to various link-local endpoints.
config=Config(signature_version=UNSIGNED)
).exceptions
from typing import Optional
from botocore.configprovider import (
ConfigValueStore,
create_botocore_default_config_mapping,
)
from botocore.errorfactory import ClientExceptionsFactory
from botocore.loaders import create_loader
from botocore.model import ServiceModel
from botocore.session import Session
from mypy_boto3_servicecatalog.literals import ServiceName
# Includes a cache for the exceptions by service.
exception_factory = ClientExceptionsFactory()
def build_service_exceptions(service_name: ServiceName, *, session: Optional[Session] = None):
"""
Build a ClientExceptions for the given service name.
"""
config_store = ConfigValueStore(
create_botocore_default_config_mapping(session or Session())
)
data_loader = create_loader(config_store.get_config_variable("data_path"))
service_model = ServiceModel(
data_loader.load_service_model(
service_name=service_name, type_name="service-2", api_version=None
),
service_name=service_name,
)
return exception_factory.create_client_exceptions(service_model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment