Enable ruff TRY401 (#114395)

* Enable ruff TRY401

* fix tests
This commit is contained in:
Sid 2024-03-29 07:20:36 +01:00 committed by GitHub
parent 530552b4f5
commit a5b609f081
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
61 changed files with 159 additions and 182 deletions

View File

@ -384,10 +384,8 @@ def async_get_entities(
try:
alexa_entity = ENTITY_ADAPTERS[state.domain](hass, config, state)
interfaces = list(alexa_entity.interfaces())
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(
"Unable to serialize %s for discovery: %s", state.entity_id, exc
)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unable to serialize %s for discovery", state.entity_id)
else:
if not interfaces:
continue

View File

@ -126,9 +126,9 @@ async def async_api_discovery(
continue
try:
discovered_serialized_entity = alexa_entity.serialize_discovery()
except Exception as exc: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Unable to serialize %s for discovery: %s", alexa_entity.entity_id, exc
"Unable to serialize %s for discovery", alexa_entity.entity_id
)
else:
discovery_endpoints.append(discovered_serialized_entity)

View File

@ -94,8 +94,8 @@ class AlexaIntentsView(http.HomeAssistantView):
)
)
except intent.IntentError as err:
_LOGGER.exception(str(err))
except intent.IntentError:
_LOGGER.exception("Error handling intent")
return self.json(
intent_error_response(hass, message, "Error handling intent.")
)

View File

@ -376,11 +376,9 @@ class PassiveBluetoothProcessorCoordinator(
try:
update = self._update_method(service_info)
except Exception as err: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
self.last_update_success = False
self.logger.exception(
"Unexpected error updating %s data: %s", self.name, err
)
self.logger.exception("Unexpected error updating %s data", self.name)
return
if not self.last_update_success:
@ -588,10 +586,10 @@ class PassiveBluetoothDataProcessor(Generic[_T]):
"""Handle a Bluetooth event."""
try:
new_data = self.update_method(update)
except Exception as err: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
self.last_update_success = False
self.coordinator.logger.exception(
"Unexpected error updating %s data: %s", self.coordinator.name, err
"Unexpected error updating %s data", self.coordinator.name
)
return

View File

@ -38,13 +38,13 @@ async def validate_input(user_input: dict[str, Any]) -> dict[str, str] | None:
_LOGGER.warning("Brunt Credentials are incorrect")
errors = {"base": "invalid_auth"}
else:
_LOGGER.exception("Unknown error when trying to login to Brunt: %s", exc)
_LOGGER.exception("Unknown error when trying to login to Brunt")
errors = {"base": "unknown"}
except ServerDisconnectedError:
_LOGGER.warning("Cannot connect to Brunt")
errors = {"base": "cannot_connect"}
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception("Unknown error when trying to login to Brunt: %s", exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error when trying to login to Brunt")
errors = {"base": "unknown"}
finally:
await bapi.async_close()

View File

@ -232,12 +232,10 @@ def async_log_errors(
func.__name__,
err,
)
except DenonAvrError as err:
except DenonAvrError:
available = False
_LOGGER.exception(
"Error %s occurred in method %s for Denon AVR receiver",
err,
func.__name__,
"Error occurred in method %s for Denon AVR receiver", func.__name__
)
finally:
if available and not self.available:

View File

@ -89,8 +89,8 @@ async def _async_try_connect(token: str) -> tuple[str | None, nextcord.AppInfo |
return "invalid_auth", None
except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound):
return "cannot_connect", None
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception: %s", ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
return "unknown", None
await discord_bot.close()
return None, info

View File

@ -121,8 +121,8 @@ class DLinkFlowHandler(ConfigFlow, domain=DOMAIN):
user_input[CONF_USERNAME],
user_input[CONF_USE_LEGACY_PROTOCOL],
)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception: %s", ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
return "unknown"
if not smartplug.authenticated and smartplug.use_legacy_protocol:
return "cannot_connect"

View File

@ -430,8 +430,8 @@ class EsphomeFlowHandler(ConfigFlow, domain=DOMAIN):
except aiohttp.ClientError as err:
_LOGGER.error("Error talking to the dashboard: %s", err)
return False
except json.JSONDecodeError as err:
_LOGGER.exception("Error parsing response from dashboard: %s", err)
except json.JSONDecodeError:
_LOGGER.exception("Error parsing response from dashboard")
return False
self._noise_psk = noise_psk

View File

@ -353,11 +353,11 @@ class RuntimeEntryData:
if subscription := self.state_subscriptions.get(subscription_key):
try:
subscription()
except Exception as ex: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
# If we allow this exception to raise it will
# make it all the way to data_received in aioesphomeapi
# which will cause the connection to be closed.
_LOGGER.exception("Error while calling subscription: %s", ex)
_LOGGER.exception("Error while calling subscription")
@callback
def async_update_device_state(self) -> None:

View File

@ -43,8 +43,8 @@ class FAADelaysConfigFlow(ConfigFlow, domain=DOMAIN):
_LOGGER.error("Error connecting to FAA API")
errors["base"] = "cannot_connect"
except Exception as error: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception: %s", error)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if not errors:

View File

@ -44,9 +44,9 @@ class FliprConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "invalid_auth"
except (Timeout, ConnectionError):
errors["base"] = "cannot_connect"
except Exception as exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
errors["base"] = "unknown"
_LOGGER.exception(exception)
_LOGGER.exception("Unexpected exception")
if not errors and not flipr_ids:
# No flipr_id found. Tell the user with an error message.

View File

@ -74,8 +74,8 @@ class FrontierSiliconConfigFlow(ConfigFlow, domain=DOMAIN):
self._webfsapi_url = await AFSAPI.get_webfsapi_endpoint(device_url)
except FSConnectionError:
errors["base"] = "cannot_connect"
except Exception as exception: # pylint: disable=broad-except
_LOGGER.exception(exception)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return await self._async_step_device_config_if_needed()
@ -206,8 +206,8 @@ class FrontierSiliconConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "cannot_connect"
except InvalidPinException:
errors["base"] = "invalid_auth"
except Exception as exception: # pylint: disable=broad-except
_LOGGER.exception(exception)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if self._reauth_entry:

View File

@ -295,7 +295,7 @@ class GoogleCloudTTSProvider(Provider):
except TimeoutError as ex:
_LOGGER.error("Timeout for Google Cloud TTS call: %s", ex)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception("Error occurred during Google Cloud TTS call: %s", ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error occurred during Google Cloud TTS call")
return None, None

View File

@ -53,7 +53,7 @@ class OAuth2FlowHandler(
reason="access_not_configured",
description_placeholders={"message": error},
)
except Exception as ex: # pylint: disable=broad-except
self.logger.exception("Unknown error occurred: %s", ex)
except Exception: # pylint: disable=broad-except
self.logger.exception("Unknown error occurred")
return self.async_abort(reason="unknown")
return self.async_create_entry(title=self.flow_impl.name, data=data)

View File

@ -162,8 +162,8 @@ class GoogleProvider(Provider):
try:
tts.write_to_fp(mp3_data)
except gTTSError as exc:
_LOGGER.exception("Error during processing of TTS request %s", exc)
except gTTSError:
_LOGGER.exception("Error during processing of TTS request")
return None, None
return "mp3", mp3_data.getvalue()

View File

@ -124,8 +124,8 @@ class HERETravelTimeConfigFlow(ConfigFlow, domain=DOMAIN):
await async_validate_api_key(user_input[CONF_API_KEY])
except HERERoutingUnauthorizedError:
errors["base"] = "invalid_auth"
except (HERERoutingError, HERETransitError) as error:
_LOGGER.exception("Unexpected exception: %s", error)
except (HERERoutingError, HERETransitError):
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if not errors:
self._config = user_input

View File

@ -201,7 +201,7 @@ class HomeWizardConfigFlow(ConfigFlow, domain=DOMAIN):
) from ex
except Exception as ex:
_LOGGER.exception(ex)
_LOGGER.exception("Unexpected exception")
raise AbortFlow("unknown_error") from ex
finally:

View File

@ -58,7 +58,7 @@ class CachingStaticResource(StaticResource):
raise
except Exception as error:
# perm error or other kind!
request.app.logger.exception(error)
request.app.logger.exception("Unexpected exception")
raise HTTPNotFound from error
content_type: str | None = None

View File

@ -40,8 +40,8 @@ class IpmaFlowHandler(ConfigFlow, domain=DOMAIN):
user_input[CONF_LATITUDE],
user_input[CONF_LONGITUDE],
)
except IPMAException as err:
_LOGGER.exception(err)
except IPMAException:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=location.name, data=user_input)

View File

@ -66,9 +66,9 @@ class JellyfinConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception as ex: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
errors["base"] = "unknown"
_LOGGER.exception(ex)
_LOGGER.exception("Unexpected exception")
else:
entry_title = user_input[CONF_URL]
@ -116,9 +116,9 @@ class JellyfinConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception as ex: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
errors["base"] = "unknown"
_LOGGER.exception(ex)
_LOGGER.exception("Unexpected exception")
else:
self.hass.config_entries.async_update_entry(self.entry, data=new_input)

View File

@ -94,7 +94,7 @@ class LitterRobotConfigFlow(ConfigFlow, domain=DOMAIN):
return "invalid_auth"
except LitterRobotException:
return "cannot_connect"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception: %s", ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
return "unknown"
return ""

View File

@ -49,8 +49,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
try:
payload = {"host": le_wh, "event": json_body}
requests.post(le_wh, data=json.dumps(payload), timeout=10)
except requests.exceptions.RequestException as error:
_LOGGER.exception("Error sending to Logentries: %s", error)
except requests.exceptions.RequestException:
_LOGGER.exception("Error sending to Logentries")
hass.bus.listen(EVENT_STATE_CHANGED, logentries_event_listener)

View File

@ -86,8 +86,8 @@ class MailgunNotificationService(BaseNotificationService):
except MailgunCredentialsError:
_LOGGER.exception("Invalid credentials")
return False
except MailgunDomainError as mailgun_error:
_LOGGER.exception(mailgun_error)
except MailgunDomainError:
_LOGGER.exception("Unexpected exception")
return False
return True
@ -110,5 +110,5 @@ class MailgunNotificationService(BaseNotificationService):
files=files,
)
_LOGGER.debug("Message sent: %s", resp)
except MailgunError as mailgun_error:
_LOGGER.exception("Failed to send message: %s", mailgun_error)
except MailgunError:
_LOGGER.exception("Failed to send message")

View File

@ -136,11 +136,10 @@ class InspectorBLEConfigFlow(ConfigFlow, domain=DOMAIN):
return self.async_abort(reason="cannot_connect")
except AbortFlow:
raise
except Exception as err: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error occurred reading information from %s: %s",
"Error occurred reading information from %s",
self._discovery_info.address,
err,
)
return self.async_abort(reason="unknown")
_LOGGER.debug("Device connection successful, proceeding")

View File

@ -121,10 +121,9 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->
try:
await api.async_initialize()
except MinecraftServerAddressError as error:
except MinecraftServerAddressError:
_LOGGER.exception(
"Can't migrate configuration entry due to error while parsing server address, try again later: %s",
error,
"Can't migrate configuration entry due to error while parsing server address, try again later"
)
return False

View File

@ -45,8 +45,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
try:
mochad_controller = MochadCtrl(host, port)
except exceptions.ConfigurationError as err:
_LOGGER.exception(str(err))
except exceptions.ConfigurationError:
_LOGGER.exception("Unexpected exception")
return False
def stop_mochad(event):

View File

@ -37,8 +37,8 @@ def get_service(
try:
return MSTeamsNotificationService(webhook_url)
except RuntimeError as err:
_LOGGER.exception("Error in creating a new Microsoft Teams message: %s", err)
except RuntimeError:
_LOGGER.exception("Error in creating a new Microsoft Teams message")
return None

View File

@ -115,11 +115,11 @@ class OctoPrintConfigFlow(ConfigFlow, domain=DOMAIN):
try:
await self.api_key_task
except OctoprintException as err:
_LOGGER.exception("Failed to get an application key: %s", err)
except OctoprintException:
_LOGGER.exception("Failed to get an application key")
return self.async_show_progress_done(next_step_id="auth_failed")
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Failed to get an application key : %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Failed to get an application key")
return self.async_show_progress_done(next_step_id="auth_failed")
finally:
self.api_key_task = None

View File

@ -83,8 +83,8 @@ def setup_platform(
host = config[CONF_HOST]
try:
bridge = Lightify(host, log_level=logging.NOTSET)
except OSError as err:
_LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err)
except OSError:
_LOGGER.exception("Error connecting to bridge %s", host)
return
setup_bridge(bridge, add_entities, config)

View File

@ -177,8 +177,8 @@ class Remote:
self._control = None
self.state = STATE_OFF
self.available = self._on_action is not None
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred")
self._control = None
self.state = STATE_OFF
self.available = self._on_action is not None
@ -265,7 +265,7 @@ class Remote:
self.state = STATE_OFF
self.available = self._on_action is not None
await self.async_create_remote_control()
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred")
self.state = STATE_OFF
self.available = self._on_action is not None

View File

@ -60,8 +60,8 @@ class PanasonicVieraConfigFlow(ConfigFlow, domain=DOMAIN):
except (URLError, SOAPError, OSError) as err:
_LOGGER.error("Could not establish remote connection: %s", err)
errors["base"] = "cannot_connect"
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("An unknown error occurred")
return self.async_abort(reason="unknown")
if "base" not in errors:
@ -118,8 +118,8 @@ class PanasonicVieraConfigFlow(ConfigFlow, domain=DOMAIN):
except (URLError, OSError) as err:
_LOGGER.error("The remote connection was lost: %s", err)
return self.async_abort(reason="cannot_connect")
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Unknown error: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error")
return self.async_abort(reason="unknown")
if "base" not in errors:
@ -142,8 +142,8 @@ class PanasonicVieraConfigFlow(ConfigFlow, domain=DOMAIN):
except (URLError, SOAPError, OSError) as err:
_LOGGER.error("The remote connection was lost: %s", err)
return self.async_abort(reason="cannot_connect")
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Unknown error: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error")
return self.async_abort(reason="unknown")
return self.async_show_form(

View File

@ -50,8 +50,7 @@ class MyPermobilCoordinator(DataUpdateCoordinator[MyPermobilData]):
except MyPermobilAPIException as err:
_LOGGER.exception(
"Error fetching data from MyPermobil API for account %s %s",
"Error fetching data from MyPermobil API for account %s",
self.p_api.email,
err,
)
raise UpdateFailed from err

View File

@ -216,8 +216,8 @@ class PlexFlowHandler(ConfigFlow, domain=DOMAIN):
self.available_servers = available_servers.args[0]
return await self.async_step_select_server()
except Exception as error: # pylint: disable=broad-except
_LOGGER.exception("Unknown error connecting to Plex server: %s", error)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error connecting to Plex server")
return self.async_abort(reason="unknown")
if errors:

View File

@ -62,8 +62,8 @@ class ProsegurConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception as exception: # pylint: disable=broad-except
_LOGGER.exception(exception)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
self.user_input = user_input

View File

@ -290,7 +290,7 @@ def execute(hass, filename, source, data=None, return_response=False):
raise HomeAssistantError(
f"Error executing script ({type(err).__name__}): {err}"
) from err
logger.exception("Error executing script: %s", err)
logger.exception("Error executing script")
return None
return restricted_globals["output"]

View File

@ -55,8 +55,8 @@ def validate_table_schema_supports_utf8(
schema_errors = _validate_table_schema_supports_utf8(
instance, table_object, columns
)
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema: %s", exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema")
_log_schema_errors(table_object, schema_errors)
return schema_errors
@ -76,8 +76,8 @@ def validate_table_schema_has_correct_collation(
schema_errors = _validate_table_schema_has_correct_collation(
instance, table_object
)
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema: %s", exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema")
_log_schema_errors(table_object, schema_errors)
return schema_errors
@ -159,8 +159,8 @@ def validate_db_schema_precision(
return schema_errors
try:
schema_errors = _validate_db_schema_precision(instance, table_object)
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema: %s", exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error when validating DB schema")
_log_schema_errors(table_object, schema_errors)
return schema_errors

View File

@ -898,8 +898,8 @@ class Recorder(threading.Thread):
_LOGGER.debug("Processing task: %s", task)
try:
self._process_one_task_or_event_or_recover(task)
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error while processing event %s: %s", task, err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error while processing event %s", task)
def _process_one_task_or_event_or_recover(self, task: RecorderTask | Event) -> None:
"""Process a task or event, reconnect, or recover a malformed database."""
@ -921,11 +921,9 @@ class Recorder(threading.Thread):
except exc.DatabaseError as err:
if self._handle_database_error(err):
return
_LOGGER.exception(
"Unhandled database error while processing task %s: %s", task, err
)
except SQLAlchemyError as err:
_LOGGER.exception("SQLAlchemyError error processing task %s: %s", task, err)
_LOGGER.exception("Unhandled database error while processing task %s", task)
except SQLAlchemyError:
_LOGGER.exception("SQLAlchemyError error processing task %s", task)
# Reset the session if an SQLAlchemyError (including DatabaseError)
# happens to rollback and recover
@ -941,10 +939,9 @@ class Recorder(threading.Thread):
return migration.initialize_database(self.get_session)
except UnsupportedDialect:
break
except Exception as err: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error during connection setup: %s (retrying in %s seconds)",
err,
"Error during connection setup: (retrying in %s seconds)",
self.db_retry_wait,
)
tries += 1
@ -1262,10 +1259,8 @@ class Recorder(threading.Thread):
try:
self.event_session.rollback()
self.event_session.close()
except SQLAlchemyError as err:
_LOGGER.exception(
"Error while rolling back and closing the event session: %s", err
)
except SQLAlchemyError:
_LOGGER.exception("Error while rolling back and closing the event session")
def _reopen_event_session(self) -> None:
"""Rollback the event session and reopen it after a failure."""
@ -1473,8 +1468,8 @@ class Recorder(threading.Thread):
self.recorder_runs_manager.end(self.event_session)
try:
self._commit_event_session_or_retry()
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error saving the event session during shutdown: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error saving the event session during shutdown")
self.event_session.close()
self.recorder_runs_manager.clear()

View File

@ -183,8 +183,8 @@ def get_schema_version(session_maker: Callable[[], Session]) -> int | None:
try:
with session_scope(session=session_maker(), read_only=True) as session:
return _get_schema_version(session)
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error when determining DB schema version: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error when determining DB schema version")
return None
@ -1786,8 +1786,8 @@ def initialize_database(session_maker: Callable[[], Session]) -> bool:
with session_scope(session=session_maker()) as session:
return _initialize_database(session)
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error when initialise database: %s", err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error when initialise database")
return False

View File

@ -18,8 +18,8 @@ def ulid_to_bytes_or_none(ulid: str | None) -> bytes | None:
return None
try:
return ulid_to_bytes(ulid)
except ValueError as ex:
_LOGGER.exception("Error converting ulid %s to bytes: %s", ulid, ex)
except ValueError:
_LOGGER.exception("Error converting ulid %s to bytes", ulid)
return None
@ -29,8 +29,8 @@ def bytes_to_ulid_or_none(_bytes: bytes | None) -> str | None:
return None
try:
return bytes_to_ulid(_bytes)
except ValueError as ex:
_LOGGER.exception("Error converting bytes %s to ulid: %s", _bytes, ex)
except ValueError:
_LOGGER.exception("Error converting bytes %s to ulid", _bytes)
return None

View File

@ -143,7 +143,7 @@ def session_scope(
need_rollback = True
session.commit()
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error executing query: %s", err)
_LOGGER.exception("Error executing query")
if need_rollback:
session.rollback()
if not exception_filter or not exception_filter(err):

View File

@ -547,9 +547,9 @@ class ReolinkHost:
self._long_poll_error = True
await asyncio.sleep(LONG_POLL_ERROR_COOLDOWN)
continue
except Exception as ex:
except Exception:
_LOGGER.exception(
"Unexpected exception while requesting ONVIF pull point: %s", ex
"Unexpected exception while requesting ONVIF pull point"
)
await self._api.unsubscribe(sub_type=SubType.long_poll)
raise
@ -652,11 +652,9 @@ class ReolinkHost:
message = data.decode("utf-8")
channels = await self._api.ONVIF_event_callback(message)
except Exception as ex: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error processing ONVIF event for Reolink %s: %s",
self._api.nvr_name,
ex,
"Error processing ONVIF event for Reolink %s", self._api.nvr_name
)
return

View File

@ -219,8 +219,8 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
req = await self.get_device_state(self.hass)
except (TimeoutError, httpx.TimeoutException):
_LOGGER.exception("Timed out while fetching data")
except httpx.RequestError as err:
_LOGGER.exception("Error while fetching data: %s", err)
except httpx.RequestError:
_LOGGER.exception("Error while fetching data")
if req:
self._process_manual_data(req.text)

View File

@ -69,11 +69,11 @@ class RoborockFlowHandler(ConfigFlow, domain=DOMAIN):
errors["base"] = "unknown_url"
except RoborockInvalidEmail:
errors["base"] = "invalid_email_format"
except RoborockException as ex:
_LOGGER.exception(ex)
except RoborockException:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown_roborock"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception(ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return errors
@ -92,11 +92,11 @@ class RoborockFlowHandler(ConfigFlow, domain=DOMAIN):
login_data = await self._client.code_login(code)
except RoborockInvalidCode:
errors["base"] = "invalid_code"
except RoborockException as ex:
_LOGGER.exception(ex)
except RoborockException:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown_roborock"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception(ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if self.reauth_entry is not None:

View File

@ -187,12 +187,10 @@ class SerialSensor(SensorEntity):
**kwargs,
)
except SerialException as exc:
except SerialException:
if not logged_error:
_LOGGER.exception(
"Unable to connect to the serial device %s: %s. Will retry",
device,
exc,
"Unable to connect to the serial device %s. Will retry", device
)
logged_error = True
await self._handle_error()
@ -201,9 +199,9 @@ class SerialSensor(SensorEntity):
while True:
try:
line = await reader.readline()
except SerialException as exc:
except SerialException:
_LOGGER.exception(
"Error while reading serial device %s: %s", device, exc
"Error while reading serial device %s", device
)
await self._handle_error()
break

View File

@ -58,8 +58,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
rendered_args = args_compiled.async_render(
variables=service.data, parse_result=False
)
except TemplateError as ex:
_LOGGER.exception("Error rendering command template: %s", ex)
except TemplateError:
_LOGGER.exception("Error rendering command template")
raise
else:
rendered_args = None

View File

@ -77,8 +77,8 @@ def validate_input(data: dict[str, Any]) -> dict[str, str] | None:
return {"base": "invalid_account_format"}
except InvalidAccountLengthError:
return {"base": "invalid_account_length"}
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception from SIAAccount: %s", exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception from SIAAccount")
return {"base": "unknown"}
if not 1 <= data[CONF_PING_INTERVAL] <= 1440:
return {"base": "invalid_ping"}

View File

@ -68,7 +68,7 @@ class SlackFlowHandler(ConfigFlow, domain=DOMAIN):
if ex.response["error"] == "invalid_auth":
return "invalid_auth", None
return "cannot_connect", None
except Exception as ex: # pylint:disable=broad-except
_LOGGER.exception("Unexpected exception: %s", ex)
except Exception: # pylint:disable=broad-except
_LOGGER.exception("Unexpected exception")
return "unknown", None
return None, info

View File

@ -104,8 +104,8 @@ class TeslaWallConnectorConfigFlow(ConfigFlow, domain=DOMAIN):
info = await validate_input(self.hass, user_input)
except WallConnectorError:
errors["base"] = "cannot_connect"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception: %s", ex)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if not errors:

View File

@ -154,7 +154,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
},
)
ir.async_delete_issue(hass, DOMAIN, "ea_channel_warning")
_LOGGER.exception("Error setting up UniFi Protect integration: %s", err)
_LOGGER.exception("Error setting up UniFi Protect integration")
raise
return True

View File

@ -45,8 +45,8 @@ async def get_by_station_number(
measuring_station = await client.get_by_station_number(station_number)
except WAQIConnectionError:
errors["base"] = "cannot_connect"
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return measuring_station, errors
@ -76,8 +76,8 @@ class WAQIConfigFlow(ConfigFlow, domain=DOMAIN):
errors["base"] = "invalid_auth"
except WAQIConnectionError:
errors["base"] = "cannot_connect"
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
self.data = user_input
@ -118,8 +118,8 @@ class WAQIConfigFlow(ConfigFlow, domain=DOMAIN):
)
except WAQIConnectionError:
errors["base"] = "cannot_connect"
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(exc)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return await self._async_create_entry(measuring_station)

View File

@ -289,7 +289,7 @@ async def handle_call_service(
translation_placeholders=err.translation_placeholders,
)
except HomeAssistantError as err:
connection.logger.exception(err)
connection.logger.exception("Unexpected exception")
connection.send_error(
msg["id"],
const.ERR_HOME_ASSISTANT_ERROR,
@ -299,7 +299,7 @@ async def handle_call_service(
translation_placeholders=err.translation_placeholders,
)
except Exception as err: # pylint: disable=broad-except
connection.logger.exception(err)
connection.logger.exception("Unexpected exception")
connection.send_error(msg["id"], const.ERR_UNKNOWN_ERROR, str(err))

View File

@ -205,7 +205,7 @@ class DeviceCoordinator(DataUpdateCoordinator[None]): # pylint: disable=hass-en
except Exception as err: # pylint: disable=broad-except
self.last_exception = err
self.last_update_success = False
_LOGGER.exception("Unexpected error fetching %s data: %s", self.name, err)
_LOGGER.exception("Unexpected error fetching %s data", self.name)
else:
self.async_set_updated_data(None)

View File

@ -126,8 +126,8 @@ class WyomingSttProvider(stt.SpeechToTextEntity):
text = transcript.text
break
except (OSError, WyomingError) as err:
_LOGGER.exception("Error processing audio stream: %s", err)
except (OSError, WyomingError):
_LOGGER.exception("Error processing audio stream")
return stt.SpeechResult(None, stt.SpeechResultState.ERROR)
return stt.SpeechResult(

View File

@ -187,8 +187,8 @@ class WyomingWakeWordProvider(wake_word.WakeWordDetectionEntity):
for task in pending:
task.cancel()
except (OSError, WyomingError) as err:
_LOGGER.exception("Error processing audio stream: %s", err)
except (OSError, WyomingError):
_LOGGER.exception("Error processing audio stream")
return None

View File

@ -1101,10 +1101,8 @@ class HomeAssistant:
_LOGGER.exception(
"Task %s could not be canceled during final shutdown stage", task
)
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(
"Task %s error during final shutdown stage: %s", task, exc
)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Task %s error during final shutdown stage", task)
# Prevent run_callback_threadsafe from scheduling any additional
# callbacks in the event loop as callbacks created on the futures

View File

@ -489,8 +489,8 @@ class FlowManager(abc.ABC, Generic[_FlowResultT, _HandlerT]):
flow.async_cancel_progress_task()
try:
flow.async_remove()
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Error removing %s flow: %s", flow.handler, err)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error removing %s flow", flow.handler)
async def _async_handle_step(
self,

View File

@ -383,9 +383,7 @@ class DataUpdateCoordinator(BaseDataUpdateCoordinatorProtocol, Generic[_DataT]):
except Exception as err: # pylint: disable=broad-except
self.last_exception = err
self.last_update_success = False
self.logger.exception(
"Unexpected error fetching %s data: %s", self.name, err
)
self.logger.exception("Unexpected error fetching %s data", self.name)
else:
if not self.last_update_success:

View File

@ -715,8 +715,7 @@ ignore = [
"PT019",
"TRY002",
"TRY301",
"TRY300",
"TRY401"
"TRY300"
]
[tool.ruff.lint.flake8-import-conventions.extend-aliases]

View File

@ -143,7 +143,7 @@ raise Exception('boom')
hass.async_add_executor_job(execute, hass, "test.py", source, {})
await hass.async_block_till_done()
assert "Error executing script: boom" in caplog.text
assert "Error executing script" in caplog.text
async def test_execute_runtime_error_with_response(hass: HomeAssistant) -> None:

View File

@ -189,7 +189,7 @@ async def test_abort_calls_async_remove_with_exception(
with caplog.at_level(logging.ERROR):
await manager.async_init("test")
assert "Error removing test flow: error" in caplog.text
assert "Error removing test flow" in caplog.text
TestFlow.async_remove.assert_called_once()