mirror of
https://github.com/home-assistant/core.git
synced 2026-08-03 20:24:55 +02:00
Cleanup unnecessary brackets for except statements (a-h) (#162404)
This commit is contained in:
@@ -64,7 +64,7 @@ class AbodeFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
else:
|
||||
errors = {"base": "cannot_connect"}
|
||||
|
||||
except (ConnectTimeout, HTTPError):
|
||||
except ConnectTimeout, HTTPError:
|
||||
errors = {"base": "cannot_connect"}
|
||||
|
||||
if errors:
|
||||
|
||||
@@ -43,7 +43,7 @@ class AccuWeatherFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
longitude=user_input[CONF_LONGITUDE],
|
||||
)
|
||||
await accuweather.async_get_location()
|
||||
except (ApiError, ClientConnectorError, TimeoutError, ClientError):
|
||||
except ApiError, ClientConnectorError, TimeoutError, ClientError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidApiKeyError:
|
||||
errors[CONF_API_KEY] = "invalid_api_key"
|
||||
@@ -104,7 +104,7 @@ class AccuWeatherFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
longitude=self._longitude,
|
||||
)
|
||||
await accuweather.async_get_location()
|
||||
except (ApiError, ClientConnectorError, TimeoutError, ClientError):
|
||||
except ApiError, ClientConnectorError, TimeoutError, ClientError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidApiKeyError:
|
||||
errors["base"] = "invalid_api_key"
|
||||
|
||||
@@ -85,7 +85,7 @@ class AirobotButton(AirobotEntity, ButtonEntity):
|
||||
"""Handle the button press."""
|
||||
try:
|
||||
await self.entity_description.press_fn(self.coordinator)
|
||||
except (AirobotConnectionError, AirobotTimeoutError):
|
||||
except AirobotConnectionError, AirobotTimeoutError:
|
||||
# Connection errors during reboot are expected as device restarts
|
||||
pass
|
||||
except AirobotError as err:
|
||||
|
||||
@@ -114,7 +114,7 @@ class AirOSConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
AirOSDeviceConnectionError,
|
||||
):
|
||||
self.errors["base"] = "cannot_connect"
|
||||
except (AirOSConnectionAuthenticationError, AirOSDataMissingError):
|
||||
except AirOSConnectionAuthenticationError, AirOSDataMissingError:
|
||||
self.errors["base"] = "invalid_auth"
|
||||
except AirOSKeyDataMissingError:
|
||||
self.errors["base"] = "key_data_missing"
|
||||
|
||||
@@ -130,7 +130,7 @@ class AirVisualFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
try:
|
||||
await coro
|
||||
except (InvalidKeyError, KeyExpiredError, UnauthorizedError):
|
||||
except InvalidKeyError, KeyExpiredError, UnauthorizedError:
|
||||
errors[CONF_API_KEY] = "invalid_api_key"
|
||||
except NotFoundError:
|
||||
errors[CONF_CITY] = "location_not_found"
|
||||
|
||||
@@ -100,7 +100,7 @@ class AirZoneCloudConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
try:
|
||||
await self.airzone.login()
|
||||
except (AirzoneCloudError, LoginError):
|
||||
except AirzoneCloudError, LoginError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
return await self.async_step_inst_pick()
|
||||
|
||||
@@ -123,7 +123,7 @@ class Auth:
|
||||
allow_redirects=True,
|
||||
)
|
||||
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
except TimeoutError, aiohttp.ClientError:
|
||||
_LOGGER.error("Timeout calling LWA to get auth token")
|
||||
return None
|
||||
|
||||
|
||||
@@ -358,7 +358,7 @@ async def async_send_changereport_message(
|
||||
"""
|
||||
try:
|
||||
token = await config.async_get_access_token()
|
||||
except (RequireRelink, NoTokenAvailable):
|
||||
except RequireRelink, NoTokenAvailable:
|
||||
await config.set_authorized(False)
|
||||
_LOGGER.error(
|
||||
"Error when sending ChangeReport to Alexa, could not get access token"
|
||||
@@ -392,7 +392,7 @@ async def async_send_changereport_message(
|
||||
allow_redirects=True,
|
||||
)
|
||||
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
except TimeoutError, aiohttp.ClientError:
|
||||
_LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id)
|
||||
return
|
||||
|
||||
@@ -549,7 +549,7 @@ async def async_send_doorbell_event_message(
|
||||
allow_redirects=True,
|
||||
)
|
||||
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
except TimeoutError, aiohttp.ClientError:
|
||||
_LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id)
|
||||
return
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ class AndroidTVRemoteConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
self._abort_if_unique_id_configured(updates={CONF_HOST: self.host})
|
||||
try:
|
||||
return await self._async_start_pair()
|
||||
except (CannotConnect, ConnectionClosed):
|
||||
except CannotConnect, ConnectionClosed:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
user_input = {}
|
||||
@@ -135,7 +135,7 @@ class AndroidTVRemoteConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
# Attempt to pair again.
|
||||
try:
|
||||
return await self._async_start_pair()
|
||||
except (CannotConnect, ConnectionClosed):
|
||||
except CannotConnect, ConnectionClosed:
|
||||
# Device doesn't respond to the specified host. Abort.
|
||||
# If we are in the user flow we could go back to the user step to allow
|
||||
# them to enter a new IP address but we cannot do that for the zeroconf
|
||||
@@ -203,7 +203,7 @@ class AndroidTVRemoteConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
if user_input is not None:
|
||||
try:
|
||||
return await self._async_start_pair()
|
||||
except (CannotConnect, ConnectionClosed):
|
||||
except CannotConnect, ConnectionClosed:
|
||||
# Device became network unreachable after discovery.
|
||||
# Abort and let discovery find it again later.
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
@@ -229,7 +229,7 @@ class AndroidTVRemoteConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
if user_input is not None:
|
||||
try:
|
||||
return await self._async_start_pair()
|
||||
except (CannotConnect, ConnectionClosed):
|
||||
except CannotConnect, ConnectionClosed:
|
||||
# Device is network unreachable. Abort.
|
||||
errors["base"] = "cannot_connect"
|
||||
return self.async_show_form(
|
||||
|
||||
@@ -73,7 +73,7 @@ async def validate_account(auth: MSOB2CAuth, account_number: str) -> str | MSOB2
|
||||
_aw = AnglianWater(authenticator=auth)
|
||||
try:
|
||||
await _aw.validate_smart_meter(account_number)
|
||||
except (InvalidAccountIdError, SmartMeterUnavailableError):
|
||||
except InvalidAccountIdError, SmartMeterUnavailableError:
|
||||
return "smart_meter_unavailable"
|
||||
return auth
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ class ConfigFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
try:
|
||||
async with asyncio.timeout(CONNECTION_TIMEOUT):
|
||||
data = APCUPSdData(await aioapcaccess.request_status(host, port))
|
||||
except (OSError, asyncio.IncompleteReadError, TimeoutError):
|
||||
except OSError, asyncio.IncompleteReadError, TimeoutError:
|
||||
errors = {"base": "cannot_connect"}
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=_SCHEMA, errors=errors
|
||||
@@ -77,7 +77,7 @@ class ConfigFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
try:
|
||||
async with asyncio.timeout(CONNECTION_TIMEOUT):
|
||||
data = APCUPSdData(await aioapcaccess.request_status(host, port))
|
||||
except (OSError, asyncio.IncompleteReadError, TimeoutError):
|
||||
except OSError, asyncio.IncompleteReadError, TimeoutError:
|
||||
errors = {"base": "cannot_connect"}
|
||||
return self.async_show_form(
|
||||
step_id="reconfigure", data_schema=_SCHEMA, errors=errors
|
||||
|
||||
@@ -547,7 +547,7 @@ class APCUPSdSensor(APCUPSdEntity, SensorEntity):
|
||||
|
||||
try:
|
||||
self._attr_native_value = dateutil.parser.parse(data)
|
||||
except (dateutil.parser.ParserError, OverflowError):
|
||||
except dateutil.parser.ParserError, OverflowError:
|
||||
# If parsing fails we should mark it as unknown, with a log for further debugging.
|
||||
_LOGGER.warning('Failed to parse date for %s: "%s"', key, data)
|
||||
self._attr_native_value = None
|
||||
|
||||
@@ -41,7 +41,7 @@ class APsystemsLocalAPIFlow(ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
try:
|
||||
device_info = await api.get_device_info()
|
||||
except (TimeoutError, ClientConnectionError):
|
||||
except TimeoutError, ClientConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(device_info.deviceId)
|
||||
|
||||
@@ -64,7 +64,7 @@ class ApSystemsDataCoordinator(DataUpdateCoordinator[ApSystemsSensorData]):
|
||||
async def _async_setup(self) -> None:
|
||||
try:
|
||||
device_info = await self.api.get_device_info()
|
||||
except (ConnectionError, TimeoutError):
|
||||
except ConnectionError, TimeoutError:
|
||||
raise UpdateFailed from None
|
||||
self.api.max_power = device_info.maxPower
|
||||
self.api.min_power = device_info.minPower
|
||||
|
||||
@@ -49,7 +49,7 @@ class ApSystemsMaxOutputNumber(ApSystemsEntity, NumberEntity):
|
||||
"""Set the state with the value fetched from the inverter."""
|
||||
try:
|
||||
status = await self._api.get_max_power()
|
||||
except (TimeoutError, ClientConnectorError):
|
||||
except TimeoutError, ClientConnectorError:
|
||||
self._attr_available = False
|
||||
else:
|
||||
self._attr_available = True
|
||||
|
||||
@@ -43,7 +43,7 @@ class ApSystemsInverterSwitch(ApSystemsEntity, SwitchEntity):
|
||||
"""Update switch status and availability."""
|
||||
try:
|
||||
status = await self._api.get_device_power_status()
|
||||
except (TimeoutError, ClientConnectionError, InverterReturnedError):
|
||||
except TimeoutError, ClientConnectionError, InverterReturnedError:
|
||||
self._attr_available = False
|
||||
else:
|
||||
self._attr_available = True
|
||||
|
||||
@@ -56,7 +56,7 @@ class AquaCellConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
refresh_token = await api.authenticate(
|
||||
user_input[CONF_EMAIL], user_input[CONF_PASSWORD]
|
||||
)
|
||||
except (ApiException, TimeoutError):
|
||||
except ApiException, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except AuthenticationFailed:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
@@ -94,7 +94,7 @@ def _retry[_SharpAquosTVDeviceT: SharpAquosTVDevice, **_P](
|
||||
try:
|
||||
func(obj, *args, **kwargs)
|
||||
break
|
||||
except (OSError, TypeError, ValueError):
|
||||
except OSError, TypeError, ValueError:
|
||||
update_retries -= 1
|
||||
if update_retries == 0:
|
||||
obj.set_state(MediaPlayerState.OFF)
|
||||
|
||||
@@ -969,7 +969,7 @@ class PipelineRun:
|
||||
metadata,
|
||||
self._speech_to_text_stream(audio_stream=stream, stt_vad=stt_vad),
|
||||
)
|
||||
except (asyncio.CancelledError, TimeoutError):
|
||||
except asyncio.CancelledError, TimeoutError:
|
||||
raise # expected
|
||||
except hass_nabucasa.auth.Unauthenticated as src_error:
|
||||
raise SpeechToTextError(
|
||||
|
||||
@@ -189,7 +189,7 @@ class AsusWrtFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
try:
|
||||
await api.async_connect()
|
||||
|
||||
except (AsusRouterError, OSError):
|
||||
except AsusRouterError, OSError:
|
||||
_LOGGER.error(
|
||||
"Error connecting to the AsusWrt router at %s using protocol %s",
|
||||
host,
|
||||
|
||||
@@ -304,7 +304,7 @@ async def _try_async_validate_config_item(
|
||||
"""Validate config item."""
|
||||
try:
|
||||
return await _async_validate_config_item(hass, config, False, True)
|
||||
except (vol.Invalid, HomeAssistantError):
|
||||
except vol.Invalid, HomeAssistantError:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ async def async_get_config_entry_diagnostics(
|
||||
account_data["allowed"], TO_REDACT_ACCOUNT_DATA_ALLOWED
|
||||
)
|
||||
|
||||
except (AttributeError, TypeError, ValueError, KeyError):
|
||||
except AttributeError, TypeError, ValueError, KeyError:
|
||||
bucket_info = {"name": "unknown", "id": "unknown"}
|
||||
account_data = {"error": "Failed to retrieve detailed account information"}
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ class BeoConfigFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
async with self._client:
|
||||
try:
|
||||
await self._client.get_beolink_self(_request_timeout=3)
|
||||
except (ClientConnectorError, TimeoutError):
|
||||
except ClientConnectorError, TimeoutError:
|
||||
return self.async_abort(reason="invalid_address")
|
||||
|
||||
self._model = discovery_info.hostname[:-16].replace("-", " ")
|
||||
|
||||
@@ -200,7 +200,7 @@ class BraviaTVCoordinator(DataUpdateCoordinator[None]):
|
||||
"device": self.config_entry.title,
|
||||
},
|
||||
) from err
|
||||
except (BraviaConnectionError, BraviaConnectionTimeout, BraviaTurnedOff):
|
||||
except BraviaConnectionError, BraviaConnectionTimeout, BraviaTurnedOff:
|
||||
self.is_on = False
|
||||
self.connected = False
|
||||
_LOGGER.debug(
|
||||
|
||||
@@ -173,7 +173,7 @@ class BroadlinkDevice[_ApiT: blk.Device = blk.Device]:
|
||||
request = partial(function, *args, **kwargs)
|
||||
try:
|
||||
return await self.hass.async_add_executor_job(request)
|
||||
except (AuthorizationError, ConnectionClosedError):
|
||||
except AuthorizationError, ConnectionClosedError:
|
||||
if not await self.async_auth():
|
||||
raise
|
||||
return await self.hass.async_add_executor_job(request)
|
||||
|
||||
@@ -337,7 +337,7 @@ class BroadlinkRemote(BroadlinkEntity, RemoteEntity, RestoreEntity):
|
||||
await asyncio.sleep(1)
|
||||
try:
|
||||
code = await device.async_request(device.api.check_data)
|
||||
except (ReadError, StorageError):
|
||||
except ReadError, StorageError:
|
||||
continue
|
||||
return b64encode(code).decode("utf8")
|
||||
|
||||
@@ -413,7 +413,7 @@ class BroadlinkRemote(BroadlinkEntity, RemoteEntity, RestoreEntity):
|
||||
await asyncio.sleep(1)
|
||||
try:
|
||||
code = await device.async_request(device.api.check_data)
|
||||
except (ReadError, StorageError):
|
||||
except ReadError, StorageError:
|
||||
continue
|
||||
return b64encode(code).decode("utf8")
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ class BrotherConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
model, serial = await validate_input(self.hass, user_input)
|
||||
except InvalidHost:
|
||||
errors[CONF_HOST] = "wrong_host"
|
||||
except (ConnectionError, TimeoutError):
|
||||
except ConnectionError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except SnmpError:
|
||||
errors["base"] = "snmp_error"
|
||||
@@ -163,7 +163,7 @@ class BrotherConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
await self.brother.async_update()
|
||||
except UnsupportedModelError:
|
||||
return self.async_abort(reason="unsupported_model")
|
||||
except (ConnectionError, SnmpError, TimeoutError):
|
||||
except ConnectionError, SnmpError, TimeoutError:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
|
||||
# Check if already configured
|
||||
@@ -211,7 +211,7 @@ class BrotherConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
await validate_input(self.hass, user_input, entry.unique_id)
|
||||
except InvalidHost:
|
||||
errors[CONF_HOST] = "wrong_host"
|
||||
except (ConnectionError, TimeoutError):
|
||||
except ConnectionError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except SnmpError:
|
||||
errors["base"] = "snmp_error"
|
||||
|
||||
@@ -199,7 +199,7 @@ class BrData:
|
||||
"""Return the temperature, or None."""
|
||||
try:
|
||||
return float(self.data.get(TEMPERATURE))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -207,7 +207,7 @@ class BrData:
|
||||
"""Return the feeltemperature, or None."""
|
||||
try:
|
||||
return float(self.data.get(FEELTEMPERATURE))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -215,7 +215,7 @@ class BrData:
|
||||
"""Return the pressure, or None."""
|
||||
try:
|
||||
return float(self.data.get(PRESSURE))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -223,7 +223,7 @@ class BrData:
|
||||
"""Return the humidity, or None."""
|
||||
try:
|
||||
return int(self.data.get(HUMIDITY))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -231,7 +231,7 @@ class BrData:
|
||||
"""Return the visibility, or None."""
|
||||
try:
|
||||
return int(self.data.get(VISIBILITY))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -239,7 +239,7 @@ class BrData:
|
||||
"""Return the windgust, or None."""
|
||||
try:
|
||||
return float(self.data.get(WINDGUST))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -247,7 +247,7 @@ class BrData:
|
||||
"""Return the windspeed, or None."""
|
||||
try:
|
||||
return float(self.data.get(WINDSPEED))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -255,7 +255,7 @@ class BrData:
|
||||
"""Return the wind bearing, or None."""
|
||||
try:
|
||||
return int(self.data.get(WINDAZIMUTH))
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
@property
|
||||
|
||||
@@ -691,7 +691,7 @@ class CalendarEventView(http.HomeAssistantView):
|
||||
try:
|
||||
start_date = dt_util.parse_datetime(start)
|
||||
end_date = dt_util.parse_datetime(end)
|
||||
except (ValueError, AttributeError):
|
||||
except ValueError, AttributeError:
|
||||
return web.Response(status=HTTPStatus.BAD_REQUEST)
|
||||
if start_date is None or end_date is None:
|
||||
return web.Response(status=HTTPStatus.BAD_REQUEST)
|
||||
|
||||
@@ -71,7 +71,7 @@ class CanaryConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
await self.hass.async_add_executor_job(
|
||||
validate_input, self.hass, user_input
|
||||
)
|
||||
except (ConnectTimeout, HTTPError):
|
||||
except ConnectTimeout, HTTPError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -373,7 +373,7 @@ class CloudAlexaConfig(alexa_config.AbstractConfig):
|
||||
if self.should_report_state:
|
||||
try:
|
||||
await self.async_enable_proactive_mode()
|
||||
except (alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink):
|
||||
except alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink:
|
||||
await self.set_authorized(False)
|
||||
else:
|
||||
await self.async_disable_proactive_mode()
|
||||
|
||||
@@ -187,7 +187,7 @@ class CloudClient(Interface):
|
||||
err,
|
||||
)
|
||||
async_call_later(self._hass, 30, enable_alexa_job)
|
||||
except (alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink):
|
||||
except alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink:
|
||||
pass
|
||||
|
||||
enable_alexa_job = HassJob(enable_alexa, cancel_on_shutdown=True)
|
||||
|
||||
@@ -779,7 +779,7 @@ async def websocket_update_prefs(
|
||||
msg["id"], "alexa_timeout", "Timeout validating Alexa access token."
|
||||
)
|
||||
return
|
||||
except (alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink):
|
||||
except alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink:
|
||||
connection.send_error(
|
||||
msg["id"],
|
||||
"alexa_relink",
|
||||
|
||||
@@ -126,5 +126,5 @@ class ComedHourlyPricingSensor(SensorEntity):
|
||||
|
||||
except (TimeoutError, aiohttp.ClientError) as err:
|
||||
_LOGGER.error("Could not get data from ComEd API: %s", err)
|
||||
except (ValueError, KeyError):
|
||||
except ValueError, KeyError:
|
||||
_LOGGER.warning("Could not update status for %s", self.name)
|
||||
|
||||
@@ -186,7 +186,7 @@ class CompensationSensor(SensorEntity):
|
||||
y_value = self._poly(x_value)
|
||||
self._attr_native_value = round(y_value, self._precision)
|
||||
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
self._attr_native_value = None
|
||||
if self._source_attribute:
|
||||
_LOGGER.warning(
|
||||
|
||||
@@ -421,7 +421,7 @@ def config_entries_flow_subscribe(
|
||||
config_entries.SOURCE_USER,
|
||||
)
|
||||
]
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
# If we can't serialize, we'll filter out unserializable flows
|
||||
serialized_flows = []
|
||||
for flw in hass.config_entries.flow.async_progress():
|
||||
@@ -434,7 +434,7 @@ def config_entries_flow_subscribe(
|
||||
serialized_flows.append(
|
||||
json_bytes({"type": None, "flow_id": flw["flow_id"], "flow": flw})
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
_LOGGER.error(
|
||||
"Unable to serialize to JSON. Bad data found at %s",
|
||||
format_unserializable_data(
|
||||
|
||||
@@ -74,7 +74,7 @@ class Control4ConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
director_bearer_token = (
|
||||
await account.getDirectorBearerToken(controller_unique_id)
|
||||
)["token"]
|
||||
except (BadCredentials, Unauthorized):
|
||||
except BadCredentials, Unauthorized:
|
||||
errors["base"] = "invalid_auth"
|
||||
return errors, data, description_placeholders
|
||||
except NotFound:
|
||||
@@ -97,7 +97,7 @@ class Control4ConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
except Unauthorized:
|
||||
errors["base"] = "director_auth_failed"
|
||||
return errors, data, description_placeholders
|
||||
except (ClientError, TimeoutError):
|
||||
except ClientError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
description_placeholders["host"] = host
|
||||
return errors, data, description_placeholders
|
||||
|
||||
@@ -93,7 +93,7 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
password=password,
|
||||
ssl_context=client_context_no_verify(),
|
||||
)
|
||||
except (TimeoutError, ClientError):
|
||||
except TimeoutError, ClientError:
|
||||
self.host = None
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
|
||||
@@ -142,7 +142,7 @@ async def validate_datadog_connection(
|
||||
try:
|
||||
client = DogStatsd(user_input[CONF_HOST], user_input[CONF_PORT])
|
||||
await hass.async_add_executor_job(client.increment, "connection_test")
|
||||
except (OSError, ValueError):
|
||||
except OSError, ValueError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
@@ -100,7 +100,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
async with asyncio.timeout(10):
|
||||
self.bridges = await deconz_discovery(session)
|
||||
|
||||
except (TimeoutError, ResponseError):
|
||||
except TimeoutError, ResponseError:
|
||||
self.bridges = []
|
||||
|
||||
if LOGGER.isEnabledFor(logging.DEBUG):
|
||||
@@ -158,7 +158,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
except LinkButtonNotPressed:
|
||||
errors["base"] = "linking_not_possible"
|
||||
|
||||
except (ResponseError, RequestError, TimeoutError):
|
||||
except ResponseError, RequestError, TimeoutError:
|
||||
errors["base"] = "no_key"
|
||||
|
||||
else:
|
||||
|
||||
@@ -87,7 +87,7 @@ class DelugeFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
try:
|
||||
await self.hass.async_add_executor_job(api.connect)
|
||||
except (ConnectionRefusedError, TimeoutError, SSLError):
|
||||
except ConnectionRefusedError, TimeoutError, SSLError:
|
||||
return "cannot_connect"
|
||||
except Exception as ex:
|
||||
_LOGGER.exception("Unexpected error")
|
||||
|
||||
@@ -199,7 +199,7 @@ class DenonAvrFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
try:
|
||||
success = await connect_denonavr.async_connect_receiver()
|
||||
except (AvrNetworkError, AvrTimoutError):
|
||||
except AvrNetworkError, AvrTimoutError:
|
||||
success = False
|
||||
if not success:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
|
||||
@@ -104,7 +104,7 @@ PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
|
||||
def _is_decimal_state(state: str) -> bool:
|
||||
try:
|
||||
Decimal(state)
|
||||
except (InvalidOperation, TypeError):
|
||||
except InvalidOperation, TypeError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
@@ -306,7 +306,7 @@ class DerivativeSensor(RestoreSensor, SensorEntity):
|
||||
Decimal(restored_data.native_value), # type: ignore[arg-type]
|
||||
self._round_digits,
|
||||
)
|
||||
except (InvalidOperation, TypeError):
|
||||
except InvalidOperation, TypeError:
|
||||
self._attr_native_value = None
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
|
||||
@@ -311,7 +311,7 @@ async def _async_get_device_automation_capabilities(
|
||||
|
||||
try:
|
||||
capabilities = await getattr(platform, function_name)(hass, automation)
|
||||
except (EntityNotFound, InvalidDeviceAutomationConfig):
|
||||
except EntityNotFound, InvalidDeviceAutomationConfig:
|
||||
return {}
|
||||
|
||||
capabilities = capabilities.copy()
|
||||
|
||||
@@ -895,7 +895,7 @@ class Device(RestoreEntity):
|
||||
try:
|
||||
self.gps = float(gps[0]), float(gps[1])
|
||||
self.gps_accuracy = gps_accuracy or 0
|
||||
except (ValueError, TypeError, IndexError):
|
||||
except ValueError, TypeError, IndexError:
|
||||
self.gps = None
|
||||
self.gps_accuracy = 0
|
||||
LOGGER.warning("Could not parse gps value for %s: %s", self.dev_id, gps)
|
||||
|
||||
@@ -87,7 +87,7 @@ async def _async_try_connect(token: str) -> tuple[str | None, nextcord.AppInfo |
|
||||
info = await discord_bot.application_info()
|
||||
except nextcord.LoginFailure:
|
||||
return "invalid_auth", None
|
||||
except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound):
|
||||
except ClientConnectorError, nextcord.HTTPException, nextcord.NotFound:
|
||||
return "cannot_connect", None
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -72,7 +72,7 @@ class DiscovergyConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
httpx_client=get_async_client(self.hass),
|
||||
authentication=BasicAuth(),
|
||||
).meters()
|
||||
except (discovergyError.HTTPError, discovergyError.DiscovergyClientError):
|
||||
except discovergyError.HTTPError, discovergyError.DiscovergyClientError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except discovergyError.InvalidLogin:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
@@ -260,7 +260,7 @@ class DlnaDmrEntity(MediaPlayerEntity):
|
||||
try:
|
||||
bootid_str = info.ssdp_headers[ssdp.ATTR_SSDP_BOOTID]
|
||||
bootid: int | None = int(bootid_str, 10)
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
bootid = None
|
||||
|
||||
if change == ssdp.SsdpChange.UPDATE:
|
||||
|
||||
@@ -234,7 +234,7 @@ class DmsDeviceSource:
|
||||
try:
|
||||
bootid_str = info.ssdp_headers[ssdp.ATTR_SSDP_BOOTID]
|
||||
bootid: int | None = int(bootid_str, 10)
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
bootid = None
|
||||
|
||||
if change == ssdp.SsdpChange.UPDATE:
|
||||
@@ -245,7 +245,7 @@ class DmsDeviceSource:
|
||||
try:
|
||||
next_bootid_str = info.ssdp_headers[ssdp.ATTR_SSDP_NEXTBOOTID]
|
||||
self._bootid = int(next_bootid_str, 10)
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
pass
|
||||
# Nothing left to do until ssdp:alive comes through
|
||||
return
|
||||
@@ -567,7 +567,7 @@ class DmsDeviceSource:
|
||||
# can_play is False).
|
||||
try:
|
||||
child_count = int(item.child_count)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
except AttributeError, TypeError, ValueError:
|
||||
child_count = 0
|
||||
can_expand = (
|
||||
bool(children) or child_count > 0 or isinstance(item, didl_lite.Container)
|
||||
|
||||
@@ -40,7 +40,7 @@ class Dremel3DPrinterConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
try:
|
||||
api = await self.hass.async_add_executor_job(Dremel3DPrinter, host)
|
||||
except (ConnectTimeout, HTTPError, JSONDecodeError):
|
||||
except ConnectTimeout, HTTPError, JSONDecodeError:
|
||||
errors = {"base": "cannot_connect"}
|
||||
except Exception: # noqa: BLE001
|
||||
LOGGER.exception("An unknown error has occurred")
|
||||
|
||||
@@ -120,7 +120,7 @@ class DSMRConnection:
|
||||
|
||||
try:
|
||||
transport, protocol = await asyncio.create_task(reader_factory())
|
||||
except (serial.SerialException, OSError):
|
||||
except serial.SerialException, OSError:
|
||||
LOGGER.exception("Error connecting to DSMR")
|
||||
return False
|
||||
|
||||
|
||||
@@ -837,7 +837,7 @@ async def async_setup_entry(
|
||||
# throttle reconnect attempts
|
||||
await asyncio.sleep(DEFAULT_RECONNECT_INTERVAL)
|
||||
|
||||
except (serial.SerialException, OSError):
|
||||
except serial.SerialException, OSError:
|
||||
# Log any error while establishing connection and drop to retry
|
||||
# connection wait
|
||||
LOGGER.exception("Error connecting to DSMR")
|
||||
|
||||
@@ -44,7 +44,7 @@ class DukeEnergyConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
auth = await api.authenticate()
|
||||
except ClientResponseError as e:
|
||||
errors["base"] = "invalid_auth" if e.status == 404 else "cannot_connect"
|
||||
except (ClientError, TimeoutError):
|
||||
except ClientError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -214,7 +214,7 @@ class DukeEnergyCoordinator(DataUpdateCoordinator[None]):
|
||||
# Make sure we don't go back too far
|
||||
if end_step < start:
|
||||
break
|
||||
except (TimeoutError, ClientError):
|
||||
except TimeoutError, ClientError:
|
||||
# ClientError is raised when there is no more data for the range
|
||||
break
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
|
||||
try:
|
||||
ebusdpy.init(server_address)
|
||||
except (TimeoutError, OSError):
|
||||
except TimeoutError, OSError:
|
||||
return False
|
||||
hass.data[EBUSD_DATA] = EbusdData(server_address, circuit)
|
||||
sensor_config = {
|
||||
|
||||
@@ -212,7 +212,7 @@ def _process_forecast(json):
|
||||
if json["windSpeed"] != ECOBEE_STATE_UNKNOWN:
|
||||
forecast[ATTR_FORECAST_NATIVE_WIND_SPEED] = int(json["windSpeed"])
|
||||
|
||||
except (ValueError, IndexError, KeyError):
|
||||
except ValueError, IndexError, KeyError:
|
||||
return None
|
||||
|
||||
if forecast:
|
||||
|
||||
@@ -64,7 +64,7 @@ class EheimDigitalConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
# At this point the main device is always set
|
||||
assert isinstance(hub.main, EheimDigitalDevice)
|
||||
await hub.close()
|
||||
except (ClientError, TimeoutError):
|
||||
except ClientError, TimeoutError:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
except Exception: # noqa: BLE001
|
||||
LOGGER.exception("Unknown exception occurred")
|
||||
@@ -118,7 +118,7 @@ class EheimDigitalConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
hub.main.mac_address, raise_on_progress=False
|
||||
)
|
||||
await hub.close()
|
||||
except (ClientError, TimeoutError):
|
||||
except ClientError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception: # noqa: BLE001
|
||||
errors["base"] = "unknown"
|
||||
@@ -164,7 +164,7 @@ class EheimDigitalConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
assert isinstance(hub.main, EheimDigitalDevice)
|
||||
await self.async_set_unique_id(hub.main.mac_address)
|
||||
await hub.close()
|
||||
except (ClientError, TimeoutError):
|
||||
except ClientError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception: # noqa: BLE001
|
||||
errors["base"] = "unknown"
|
||||
|
||||
@@ -168,7 +168,7 @@ class ElmaxConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
try:
|
||||
await client.login()
|
||||
except (ElmaxNetworkError, httpx.ConnectError, httpx.ConnectTimeout):
|
||||
except ElmaxNetworkError, httpx.ConnectError, httpx.ConnectTimeout:
|
||||
return self.async_show_form(
|
||||
step_id=CONF_ELMAX_MODE_DIRECT,
|
||||
data_schema=DIRECT_SETUP_SCHEMA,
|
||||
|
||||
@@ -35,7 +35,7 @@ class EGPSConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
currently_configured = self._async_current_ids(include_ignore=True)
|
||||
try:
|
||||
found_devices = await self.hass.async_add_executor_job(search_for_devices)
|
||||
except (MissingLibrary, UsbError):
|
||||
except MissingLibrary, UsbError:
|
||||
LOGGER.exception("Unable to access USB devices")
|
||||
return self.async_abort(reason="usb_error")
|
||||
|
||||
|
||||
@@ -225,7 +225,7 @@ def update_listeners(hass: HomeAssistant, entry: EnergyIDConfigEntry) -> None:
|
||||
value = float(current_state.state)
|
||||
timestamp = current_state.last_updated or dt.datetime.now(dt.UTC)
|
||||
client.get_or_create_sensor(energyid_key).update(value, timestamp)
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
_LOGGER.debug(
|
||||
"Could not convert initial state of %s to float: %s",
|
||||
ha_entity_id,
|
||||
@@ -357,7 +357,7 @@ def _async_handle_state_change(
|
||||
|
||||
try:
|
||||
value = float(new_state.state)
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return
|
||||
|
||||
client.get_or_create_sensor(energyid_key).update(value, new_state.last_updated)
|
||||
|
||||
@@ -71,7 +71,7 @@ class EnvironmentCanadaConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
if user_input is not None:
|
||||
try:
|
||||
info = await validate_input(user_input)
|
||||
except (ET.ParseError, vol.MultipleInvalid, ec_exc.UnknownStationId):
|
||||
except ET.ParseError, vol.MultipleInvalid, ec_exc.UnknownStationId:
|
||||
errors["base"] = "bad_station_id"
|
||||
except aiohttp.ClientConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
|
||||
@@ -33,7 +33,7 @@ class EssentConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
try:
|
||||
await client.async_get_prices()
|
||||
except (EssentConnectionError, EssentResponseError):
|
||||
except EssentConnectionError, EssentResponseError:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
except EssentDataError:
|
||||
return self.async_abort(reason="invalid_data")
|
||||
|
||||
@@ -296,13 +296,13 @@ class EzvizConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
try:
|
||||
return await self._validate_and_create_camera_rtsp(user_input)
|
||||
|
||||
except (InvalidHost, InvalidURL):
|
||||
except InvalidHost, InvalidURL:
|
||||
errors["base"] = "invalid_host"
|
||||
|
||||
except EzvizAuthVerificationCode:
|
||||
errors["base"] = "mfa_required"
|
||||
|
||||
except (PyEzvizError, AuthTestResultFailed):
|
||||
except PyEzvizError, AuthTestResultFailed:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
except Exception:
|
||||
@@ -357,13 +357,13 @@ class EzvizConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
_validate_and_create_auth, user_input
|
||||
)
|
||||
|
||||
except (InvalidHost, InvalidURL):
|
||||
except InvalidHost, InvalidURL:
|
||||
errors["base"] = "invalid_host"
|
||||
|
||||
except EzvizAuthVerificationCode:
|
||||
errors["base"] = "mfa_required"
|
||||
|
||||
except (PyEzvizError, AuthTestResultFailed):
|
||||
except PyEzvizError, AuthTestResultFailed:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
except Exception:
|
||||
|
||||
@@ -121,7 +121,7 @@ class EzvizNumber(EzvizBaseEntity, NumberEntity):
|
||||
str(self.sensitivity_type),
|
||||
)
|
||||
|
||||
except (EzvizAuthTokenExpired, EzvizAuthVerificationCode):
|
||||
except EzvizAuthTokenExpired, EzvizAuthVerificationCode:
|
||||
_LOGGER.debug("Failed to login to EZVIZ API")
|
||||
self.hass.async_create_task(
|
||||
self.hass.config_entries.async_reload(self.config_entry_id)
|
||||
|
||||
@@ -129,5 +129,5 @@ class BanLogParser:
|
||||
with open(self.log_file, encoding="utf-8") as file_data:
|
||||
self.data = self.ip_regex[jail].findall(file_data.read())
|
||||
|
||||
except (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):
|
||||
except IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError:
|
||||
_LOGGER.warning("File not present: %s", os.path.basename(self.log_file))
|
||||
|
||||
@@ -284,7 +284,7 @@ class FibaroController:
|
||||
last_endpoint = device.endpoint_id
|
||||
else:
|
||||
_LOGGER.debug("not handling separately")
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ class FileSensor(SensorEntity):
|
||||
data = line
|
||||
break
|
||||
data = data.strip()
|
||||
except (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):
|
||||
except IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError:
|
||||
_LOGGER.warning(
|
||||
"File or data not present at the moment: %s",
|
||||
os.path.basename(self._file_path),
|
||||
|
||||
@@ -81,5 +81,5 @@ def get_icon_from_type(type: str) -> str:
|
||||
"""Return the right icon based on the type."""
|
||||
try:
|
||||
return DeviceType[type].value
|
||||
except (ValueError, KeyError):
|
||||
except ValueError, KeyError:
|
||||
return "mdi:lan-connect"
|
||||
|
||||
@@ -173,7 +173,7 @@ class FireServiceRotaClient:
|
||||
|
||||
try:
|
||||
return await self._hass.async_add_executor_job(func, *args)
|
||||
except (ExpiredTokenError, InvalidTokenError):
|
||||
except ExpiredTokenError, InvalidTokenError:
|
||||
await self._hass.async_add_executor_job(self.websocket.stop_listener)
|
||||
self.token_refresh_failure = True
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ class FlexitBacnetConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
try:
|
||||
await device.update()
|
||||
except (asyncio.exceptions.TimeoutError, ConnectionError, DecodingError):
|
||||
except asyncio.exceptions.TimeoutError, ConnectionError, DecodingError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -45,7 +45,7 @@ class FliprConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
ids = await self.hass.async_add_executor_job(client.search_all_ids)
|
||||
except HTTPError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except (Timeout, ConnectionError):
|
||||
except Timeout, ConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
errors["base"] = "unknown"
|
||||
|
||||
@@ -388,7 +388,7 @@ class ForkedDaapdMaster(MediaPlayerEntity):
|
||||
for track in self._queue["items"]
|
||||
if track["id"] == self._player["item_id"]
|
||||
)
|
||||
except (StopIteration, TypeError, KeyError):
|
||||
except StopIteration, TypeError, KeyError:
|
||||
_LOGGER.debug("Could not get track info")
|
||||
self._track_info = defaultdict(str)
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ class GeniusHubConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
errors["base"] = "invalid_auth"
|
||||
else:
|
||||
errors["base"] = "invalid_host"
|
||||
except (TimeoutError, aiohttp.ClientConnectionError):
|
||||
except TimeoutError, aiohttp.ClientConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
@@ -111,7 +111,7 @@ class GeniusHubConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
errors["base"] = "invalid_host"
|
||||
except socket.gaierror:
|
||||
errors["base"] = "invalid_host"
|
||||
except (TimeoutError, aiohttp.ClientConnectionError):
|
||||
except TimeoutError, aiohttp.ClientConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -64,7 +64,7 @@ class SRPAuthImplementation(config_entry_oauth2_flow.AbstractOAuth2Implementatio
|
||||
if resp.status >= 400:
|
||||
try:
|
||||
error_response = await resp.json()
|
||||
except (ClientError, JSONDecodeError):
|
||||
except ClientError, JSONDecodeError:
|
||||
error_response = {}
|
||||
error_code = error_response.get("error", "unknown")
|
||||
error_description = error_response.get(
|
||||
|
||||
@@ -60,14 +60,14 @@ class GiosFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
# raising errors.
|
||||
data={**user_input, CONF_NAME: gios.station_name},
|
||||
)
|
||||
except (ApiError, ClientConnectorError, TimeoutError):
|
||||
except ApiError, ClientConnectorError, TimeoutError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidSensorsDataError:
|
||||
errors[CONF_STATION_ID] = "invalid_sensors_data"
|
||||
|
||||
try:
|
||||
gios = await Gios.create(websession)
|
||||
except (ApiError, ClientConnectorError, NoStationError):
|
||||
except ApiError, ClientConnectorError, NoStationError:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
|
||||
options: list[SelectOptionDict] = [
|
||||
|
||||
@@ -93,7 +93,7 @@ class GlancesFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
await get_api(self.hass, user_input)
|
||||
except GlancesApiAuthorizationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except (GlancesApiConnectionError, ServerVersionMismatch):
|
||||
except GlancesApiConnectionError, ServerVersionMismatch:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
return self.async_create_entry(
|
||||
|
||||
@@ -45,7 +45,7 @@ async def async_setup_entry(
|
||||
# read current time from the inverter
|
||||
try:
|
||||
await inverter.read_setting("time")
|
||||
except (InverterError, ValueError):
|
||||
except InverterError, ValueError:
|
||||
# Inverter model does not support clock synchronization
|
||||
_LOGGER.debug("Could not read inverter current clock time")
|
||||
else:
|
||||
|
||||
@@ -98,7 +98,7 @@ async def async_setup_entry(
|
||||
for description in filter(lambda dsc: dsc.filter(inverter), NUMBERS):
|
||||
try:
|
||||
current_value = await description.getter(inverter)
|
||||
except (InverterError, ValueError):
|
||||
except InverterError, ValueError:
|
||||
# Inverter model does not support this setting
|
||||
_LOGGER.debug("Could not read inverter setting %s", description.key)
|
||||
continue
|
||||
|
||||
@@ -50,7 +50,7 @@ async def async_setup_entry(
|
||||
# read current operating mode from the inverter
|
||||
try:
|
||||
active_mode = await inverter.get_operation_mode()
|
||||
except (InverterError, ValueError):
|
||||
except InverterError, ValueError:
|
||||
# Inverter model does not support this setting
|
||||
_LOGGER.debug("Could not read inverter operation mode")
|
||||
else:
|
||||
|
||||
@@ -283,7 +283,7 @@ class GoogleConfig(AbstractConfig):
|
||||
except ClientResponseError as error:
|
||||
_LOGGER.error("Request for %s failed: %d", url, error.status)
|
||||
return error.status
|
||||
except (TimeoutError, ClientError):
|
||||
except TimeoutError, ClientError:
|
||||
_LOGGER.error("Could not contact %s", url)
|
||||
return HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ def convert_to_waypoint(hass: HomeAssistant, location: str) -> Waypoint | None:
|
||||
try:
|
||||
formatted_coordinates = coordinates.split(",")
|
||||
vol.Schema(cv.gps(formatted_coordinates))
|
||||
except (AttributeError, vol.Invalid):
|
||||
except AttributeError, vol.Invalid:
|
||||
return Waypoint(address=location)
|
||||
return Waypoint(
|
||||
location=Location(
|
||||
|
||||
@@ -184,7 +184,7 @@ class GoogleWifiAPI:
|
||||
self.raw_data = response.json()
|
||||
self.data_format()
|
||||
self.available = True
|
||||
except (ValueError, requests.exceptions.ConnectionError):
|
||||
except ValueError, requests.exceptions.ConnectionError:
|
||||
_LOGGER.warning("Unable to fetch data from Google Wifi")
|
||||
self.available = False
|
||||
self.raw_data = None
|
||||
|
||||
@@ -433,7 +433,7 @@ class SensorGroup(GroupEntity, SensorEntity):
|
||||
self.entity_id,
|
||||
)
|
||||
continue
|
||||
except (KeyError, HomeAssistantError):
|
||||
except KeyError, HomeAssistantError:
|
||||
# This exception handling can be simplified
|
||||
# once sensor entity doesn't allow incorrect unit of measurement
|
||||
# with a device class, implementation see PR #107639
|
||||
|
||||
@@ -381,7 +381,7 @@ class GrowattCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
parts = str(time_raw).split(":")
|
||||
hour = int(parts[0])
|
||||
minute = int(parts[1])
|
||||
except (ValueError, IndexError):
|
||||
except ValueError, IndexError:
|
||||
return "00:00"
|
||||
else:
|
||||
return f"{hour:02d}:{minute:02d}"
|
||||
|
||||
@@ -350,7 +350,7 @@ class HabiticaConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
except NotAuthorizedError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except (HabiticaException, ClientError):
|
||||
except HabiticaException, ClientError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
@@ -379,7 +379,7 @@ class HabiticaConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
user = await api.get_user(user_fields="profile")
|
||||
except NotAuthorizedError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except (HabiticaException, ClientError):
|
||||
except HabiticaException, ClientError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
|
||||
@@ -42,7 +42,7 @@ class HannaConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
user_input[CONF_EMAIL],
|
||||
user_input[CONF_PASSWORD],
|
||||
)
|
||||
except (Timeout, RequestsConnectionError):
|
||||
except Timeout, RequestsConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except AuthenticationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
@@ -130,7 +130,7 @@ class HERETravelTimeConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
await async_validate_api_key(user_input[CONF_API_KEY])
|
||||
except HERERoutingUnauthorizedError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except (HERERoutingError, HERETransitError):
|
||||
except HERERoutingError, HERETransitError:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
if not errors:
|
||||
|
||||
@@ -91,7 +91,7 @@ def _async_create_update_entity(
|
||||
entity_description = FIRMWARE_ENTITY_DESCRIPTIONS[
|
||||
ApplicationType(firmware_type)
|
||||
]
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
_LOGGER.debug(
|
||||
"Unknown firmware type %r, using default entity description", firmware_type
|
||||
)
|
||||
|
||||
@@ -109,7 +109,7 @@ def _async_create_update_entity(
|
||||
entity_description = FIRMWARE_ENTITY_DESCRIPTIONS[
|
||||
ApplicationType(firmware_type)
|
||||
]
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
_LOGGER.debug(
|
||||
"Unknown firmware type %r, using default entity description", firmware_type
|
||||
)
|
||||
|
||||
@@ -107,7 +107,7 @@ def _async_create_update_entity(
|
||||
entity_description = FIRMWARE_ENTITY_DESCRIPTIONS[
|
||||
ApplicationType(firmware_type)
|
||||
]
|
||||
except (KeyError, ValueError):
|
||||
except KeyError, ValueError:
|
||||
_LOGGER.debug(
|
||||
"Unknown firmware type %r, using default entity description", firmware_type
|
||||
)
|
||||
|
||||
@@ -455,7 +455,7 @@ def convert_to_float(state: Any) -> float | None:
|
||||
"""Return float of state, catch errors."""
|
||||
try:
|
||||
return float(state)
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return None
|
||||
|
||||
|
||||
@@ -463,7 +463,7 @@ def coerce_int(state: str) -> int:
|
||||
"""Return int."""
|
||||
try:
|
||||
return int(state)
|
||||
except (ValueError, TypeError):
|
||||
except ValueError, TypeError:
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -965,7 +965,7 @@ class HKDevice:
|
||||
# visible on the network.
|
||||
self.async_set_available_state(False)
|
||||
return
|
||||
except (AccessoryDisconnectedError, EncryptionError):
|
||||
except AccessoryDisconnectedError, EncryptionError:
|
||||
# Temporary connection failure. Device may still available but our
|
||||
# connection was dropped or we are reconnecting
|
||||
self._poll_failures += 1
|
||||
|
||||
@@ -581,7 +581,7 @@ def _hm_event_handler(hass, interface, device, caller, attribute, value):
|
||||
channel = int(device.split(":")[1])
|
||||
address = device.split(":")[0]
|
||||
hmdevice = hass.data[DATA_HOMEMATIC].devices[interface].get(address)
|
||||
except (TypeError, ValueError):
|
||||
except TypeError, ValueError:
|
||||
_LOGGER.error("Event handling channel convert error!")
|
||||
return
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ class HTML5ConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
# we will always generate the corresponding public key
|
||||
try:
|
||||
data[ATTR_VAPID_PUB_KEY] = vapid_get_public_key(data[ATTR_VAPID_PRV_KEY])
|
||||
except (ValueError, binascii.Error):
|
||||
except ValueError, binascii.Error:
|
||||
errors[ATTR_VAPID_PRV_KEY] = "invalid_prv_key"
|
||||
|
||||
if not errors:
|
||||
|
||||
@@ -79,7 +79,7 @@ class HueBridge:
|
||||
async with asyncio.timeout(10):
|
||||
await self.api.initialize()
|
||||
setup_ok = True
|
||||
except (LinkButtonNotPressed, Unauthorized):
|
||||
except LinkButtonNotPressed, Unauthorized:
|
||||
# Usernames can become invalid if hub is reset or user removed.
|
||||
# We are going to fail the config entry setup and initiate a new
|
||||
# linking procedure. When linking succeeds, it will remove the
|
||||
|
||||
@@ -315,7 +315,7 @@ class HueFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
api = HueBridgeV2(bridge.host, conf_entry.data[CONF_API_KEY])
|
||||
try:
|
||||
await api.fetch_full_state()
|
||||
except (AiohueException, aiohttp.ClientError):
|
||||
except AiohueException, aiohttp.ClientError:
|
||||
continue
|
||||
old_bridge_id = conf_entry.unique_id
|
||||
assert old_bridge_id is not None
|
||||
|
||||
@@ -78,7 +78,7 @@ def _pin_valid(pin: str) -> bool:
|
||||
"""Check if the pin is valid."""
|
||||
try:
|
||||
int(pin)
|
||||
except (TypeError, ValueError):
|
||||
except TypeError, ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -261,7 +261,7 @@ class HusqvarnaAutomowerBleConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
except (TimeoutError, BleakError):
|
||||
except TimeoutError, BleakError:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
|
||||
return self.async_create_entry(
|
||||
@@ -325,7 +325,7 @@ class HusqvarnaAutomowerBleConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
data=reauth_entry.data | {CONF_PIN: self.pin},
|
||||
)
|
||||
|
||||
except (TimeoutError, BleakError):
|
||||
except TimeoutError, BleakError:
|
||||
# We don't want to abort a reauth flow when we can't connect, so
|
||||
# we just show the form again with an error.
|
||||
errors["base"] = "cannot_connect"
|
||||
|
||||
@@ -43,7 +43,7 @@ class HuumConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
session=async_get_clientsession(self.hass),
|
||||
)
|
||||
await huum.status()
|
||||
except (Forbidden, NotAuthenticated):
|
||||
except Forbidden, NotAuthenticated:
|
||||
# Most likely Forbidden as that is what is returned from `.status()` with bad creds
|
||||
_LOGGER.error("Could not log in to Huum with given credentials")
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
Reference in New Issue
Block a user