# Buggy code
async def wrapper(*args, **kwargs) -> Any:
    try:
        result = await func(*args, **kwargs)
    except AlexapyLoginError as ex:  # pylint: disable=broad-except
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        _LOGGER.debug(
            "%s.%s: detected bad login: %s",
            func.__module__[func.__module__.find(".") + 1 :],
            func.__name__,
            message,
        )
        instance = args[0]
        if hasattr(instance, "_login"):
            login = instance._login
            email = login.email
            hass = instance.hass if instance.hass else None
            if (
                hass
                and not (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["configurator"])
            ):
                config_entry = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "config_entry"
                ]
                callback = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "setup_platform_callback"
                ]
                test_login_status = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "test_login_status"
                ]
                _LOGGER.debug(
                    "%s: Alexa API disconnected; attempting to relogin",
                    hide_email(email),
                )
                await login.login_with_cookie()
                await test_login_status(hass, config_entry, login, callback)
        return None
    return result


# Traceback (alexapy.errors.AlexapyLoginError)
2019-10-09 15:58:30 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection.139875941900688] 'configurator'
Traceback (most recent call last):
File "/config/custom_components/alexa_media/helpers.py", line 143, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 796, in async_play_media
customer_id=self._customer_id, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 291, in play_music
musicProviderId=provider_id)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 208, in send_sequence
data=data)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 90, in _post_request
return await self._request('post', uri, data)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 82, in _request
raise AlexapyLoginError(response.reason)
alexapy.errors.AlexapyLoginError: Unauthorized

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 130, in handle_call_service
connection.context(msg),
File "/usr/src/homeassistant/homeassistant/core.py", line 1234, in async_call
await asyncio.shield(self._execute_service(handler, service_call))
File "/usr/src/homeassistant/homeassistant/core.py", line 1259, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 213, in handle_service
self._platforms.values(), func, call, service_name, required_features
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 349, in entity_service_call
future.result()  # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 373, in _handle_service_platform_call
await func(entity, data)
File "/config/custom_components/alexa_media/helpers.py", line 159, in wrapper
['configurator'])):
KeyError: 'configurator'

# Fixed code
async def wrapper(*args, **kwargs) -> Any:
    try:
        result = await func(*args, **kwargs)
    except AlexapyLoginError as ex:  # pylint: disable=broad-except
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        _LOGGER.debug(
            "%s.%s: detected bad login: %s",
            func.__module__[func.__module__.find(".") + 1 :],
            func.__name__,
            message,
        )
        instance = args[0]
        if hasattr(instance, "_login"):
            login = instance._login
            email = login.email
            hass = instance.hass if instance.hass else None
            if hass and (
                "configurator" not in (hass.data[DATA_ALEXAMEDIA]["accounts"][email])
                or not (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["configurator"])
            ):
                config_entry = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "config_entry"
                ]
                callback = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "setup_platform_callback"
                ]
                test_login_status = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "test_login_status"
                ]
                _LOGGER.debug(
                    "%s: Alexa API disconnected; attempting to relogin",
                    hide_email(email),
                )
                await login.login_with_cookie()
                await test_login_status(hass, config_entry, login, callback)
        return None
    return result