diff --git a/homeassistant/components/alexa/smart_home.py b/homeassistant/components/alexa/smart_home.py index 57c1ba791ba..d7bcfa5698e 100644 --- a/homeassistant/components/alexa/smart_home.py +++ b/homeassistant/components/alexa/smart_home.py @@ -194,7 +194,7 @@ async def async_handle_message( try: if not enabled: - raise AlexaBridgeUnreachableError( + raise AlexaBridgeUnreachableError( # noqa: TRY301 "Alexa API not enabled in Home Assistant configuration" ) diff --git a/homeassistant/components/amcrest/camera.py b/homeassistant/components/amcrest/camera.py index b9b2701eac6..0bf02b604f1 100644 --- a/homeassistant/components/amcrest/camera.py +++ b/homeassistant/components/amcrest/camera.py @@ -499,7 +499,7 @@ class AmcrestCam(Camera): await getattr(self, f"_async_set_{func}")(value) new_value = await getattr(self, f"_async_get_{func}")() if new_value != value: - raise AmcrestCommandFailed + raise AmcrestCommandFailed # noqa: TRY301 except (AmcrestError, AmcrestCommandFailed) as error: if tries == 1: log_update_error(_LOGGER, action, self.name, description, error) diff --git a/homeassistant/components/camera/__init__.py b/homeassistant/components/camera/__init__.py index d8fa4bfbc7a..cbcf08cb7c2 100644 --- a/homeassistant/components/camera/__init__.py +++ b/homeassistant/components/camera/__init__.py @@ -862,7 +862,7 @@ class CameraMjpegStream(CameraView): # Compose camera stream from stills interval = float(interval_str) if interval < MIN_STREAM_INTERVAL: - raise ValueError(f"Stream interval must be > {MIN_STREAM_INTERVAL}") + raise ValueError(f"Stream interval must be > {MIN_STREAM_INTERVAL}") # noqa: TRY301 return await camera.handle_async_still_stream(request, interval) except ValueError as err: raise web.HTTPBadRequest from err diff --git a/homeassistant/components/control4/config_flow.py b/homeassistant/components/control4/config_flow.py index f6d746c9cb4..f6eb410cbf2 100644 --- a/homeassistant/components/control4/config_flow.py +++ b/homeassistant/components/control4/config_flow.py @@ -105,9 +105,9 @@ class Control4ConfigFlow(ConfigFlow, domain=DOMAIN): ) try: if not await hub.authenticate(): - raise InvalidAuth + raise InvalidAuth # noqa: TRY301 if not await hub.connect_to_director(): - raise CannotConnect + raise CannotConnect # noqa: TRY301 except InvalidAuth: errors["base"] = "invalid_auth" except CannotConnect: diff --git a/homeassistant/components/currencylayer/sensor.py b/homeassistant/components/currencylayer/sensor.py index 2ad0f88a2ab..01dec10efe0 100644 --- a/homeassistant/components/currencylayer/sensor.py +++ b/homeassistant/components/currencylayer/sensor.py @@ -108,7 +108,7 @@ class CurrencylayerData: try: result = requests.get(self._resource, params=self._parameters, timeout=10) if "error" in result.json(): - raise ValueError(result.json()["error"]["info"]) + raise ValueError(result.json()["error"]["info"]) # noqa: TRY301 self.data = result.json()["quotes"] _LOGGER.debug("Currencylayer data updated: %s", result.json()["timestamp"]) except ValueError as err: diff --git a/homeassistant/components/device_tracker/legacy.py b/homeassistant/components/device_tracker/legacy.py index ac168c06fb1..15cb67f5ee8 100644 --- a/homeassistant/components/device_tracker/legacy.py +++ b/homeassistant/components/device_tracker/legacy.py @@ -350,7 +350,7 @@ class DeviceTrackerPlatform: discovery_info, ) else: - raise HomeAssistantError("Invalid legacy device_tracker platform.") + raise HomeAssistantError("Invalid legacy device_tracker platform.") # noqa: TRY301 if scanner is not None: async_setup_scanner_platform( diff --git a/homeassistant/components/dunehd/config_flow.py b/homeassistant/components/dunehd/config_flow.py index 8a0f3eec4a0..33ffd4a812a 100644 --- a/homeassistant/components/dunehd/config_flow.py +++ b/homeassistant/components/dunehd/config_flow.py @@ -39,7 +39,7 @@ class DuneHDConfigFlow(ConfigFlow, domain=DOMAIN): try: if self.host_already_configured(host): - raise AlreadyConfigured + raise AlreadyConfigured # noqa: TRY301 await self.init_device(host) except CannotConnect: errors[CONF_HOST] = "cannot_connect" diff --git a/homeassistant/components/egardia/__init__.py b/homeassistant/components/egardia/__init__.py index 9ff4b9af94f..89dae7d23c9 100644 --- a/homeassistant/components/egardia/__init__.py +++ b/homeassistant/components/egardia/__init__.py @@ -113,7 +113,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool: server = egardiaserver.EgardiaServer("", rs_port) bound = server.bind() if not bound: - raise OSError( + raise OSError( # noqa: TRY301 "Binding error occurred while starting EgardiaServer." ) hass.data[EGARDIA_SERVER] = server diff --git a/homeassistant/components/elmax/config_flow.py b/homeassistant/components/elmax/config_flow.py index 2971a425663..69f69a5fd31 100644 --- a/homeassistant/components/elmax/config_flow.py +++ b/homeassistant/components/elmax/config_flow.py @@ -424,7 +424,7 @@ class ElmaxConfigFlow(ConfigFlow, domain=DOMAIN): if p.hash == self._entry.data[CONF_ELMAX_PANEL_ID] ] if len(panels) < 1: - raise NoOnlinePanelsError + raise NoOnlinePanelsError # noqa: TRY301 # Verify the pin is still valid. await client.get_panel_status( diff --git a/homeassistant/components/generic_thermostat/climate.py b/homeassistant/components/generic_thermostat/climate.py index c142d15f9e5..2a118b70879 100644 --- a/homeassistant/components/generic_thermostat/climate.py +++ b/homeassistant/components/generic_thermostat/climate.py @@ -485,7 +485,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity): try: cur_temp = float(state.state) if not math.isfinite(cur_temp): - raise ValueError(f"Sensor has illegal state {state.state}") + raise ValueError(f"Sensor has illegal state {state.state}") # noqa: TRY301 self._cur_temp = cur_temp except ValueError as ex: _LOGGER.error("Unable to update from sensor: %s", ex) diff --git a/homeassistant/components/group/sensor.py b/homeassistant/components/group/sensor.py index eaaedcf0e46..a99ed9dad63 100644 --- a/homeassistant/components/group/sensor.py +++ b/homeassistant/components/group/sensor.py @@ -406,7 +406,7 @@ class SensorGroup(GroupEntity, SensorEntity): and (uom := state.attributes["unit_of_measurement"]) not in self._valid_units ): - raise HomeAssistantError("Not a valid unit") + raise HomeAssistantError("Not a valid unit") # noqa: TRY301 sensor_values.append((entity_id, numeric_state, state)) if entity_id in self._state_incorrect: diff --git a/homeassistant/components/icloud/account.py b/homeassistant/components/icloud/account.py index 988073384f8..9536cd9ee5c 100644 --- a/homeassistant/components/icloud/account.py +++ b/homeassistant/components/icloud/account.py @@ -117,7 +117,7 @@ class IcloudAccount: if self.api.requires_2fa: # Trigger a new log in to ensure the user enters the 2FA code again. - raise PyiCloudFailedLoginException + raise PyiCloudFailedLoginException # noqa: TRY301 except PyiCloudFailedLoginException: self.api = None diff --git a/homeassistant/components/icloud/config_flow.py b/homeassistant/components/icloud/config_flow.py index 36fe880ec79..30942ce6727 100644 --- a/homeassistant/components/icloud/config_flow.py +++ b/homeassistant/components/icloud/config_flow.py @@ -141,7 +141,7 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN): getattr, self.api, "devices" ) if not devices: - raise PyiCloudNoDevicesException + raise PyiCloudNoDevicesException # noqa: TRY301 except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException): _LOGGER.error("No device found in the iCloud account: %s", self._username) self.api = None @@ -264,13 +264,13 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN): if not await self.hass.async_add_executor_job( self.api.validate_2fa_code, self._verification_code ): - raise PyiCloudException("The code you entered is not valid.") + raise PyiCloudException("The code you entered is not valid.") # noqa: TRY301 elif not await self.hass.async_add_executor_job( self.api.validate_verification_code, self._trusted_device, self._verification_code, ): - raise PyiCloudException("The code you entered is not valid.") + raise PyiCloudException("The code you entered is not valid.") # noqa: TRY301 except PyiCloudException as error: # Reset to the initial 2FA state to allow the user to retry _LOGGER.error("Failed to verify verification code: %s", error) diff --git a/homeassistant/components/idasen_desk/__init__.py b/homeassistant/components/idasen_desk/__init__.py index f0d8013cb50..56a377ac2df 100644 --- a/homeassistant/components/idasen_desk/__init__.py +++ b/homeassistant/components/idasen_desk/__init__.py @@ -54,7 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: try: if not await coordinator.async_connect(): - raise ConfigEntryNotReady(f"Unable to connect to desk {address}") + raise ConfigEntryNotReady(f"Unable to connect to desk {address}") # noqa: TRY301 except (AuthFailedError, TimeoutError, BleakError, Exception) as ex: raise ConfigEntryNotReady(f"Unable to connect to desk {address}") from ex diff --git a/homeassistant/components/jvc_projector/config_flow.py b/homeassistant/components/jvc_projector/config_flow.py index 7564d571d3b..7fbfb17a976 100644 --- a/homeassistant/components/jvc_projector/config_flow.py +++ b/homeassistant/components/jvc_projector/config_flow.py @@ -37,7 +37,7 @@ class JvcProjectorConfigFlow(ConfigFlow, domain=DOMAIN): try: if not is_host_valid(host): - raise InvalidHost + raise InvalidHost # noqa: TRY301 mac = await get_mac_address(host, port, password) except InvalidHost: diff --git a/homeassistant/components/kaleidescape/config_flow.py b/homeassistant/components/kaleidescape/config_flow.py index bb9f47ec1e8..e4a562dc00b 100644 --- a/homeassistant/components/kaleidescape/config_flow.py +++ b/homeassistant/components/kaleidescape/config_flow.py @@ -38,7 +38,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN): try: info = await validate_host(host) if info.server_only: - raise UnsupportedError + raise UnsupportedError # noqa: TRY301 except ConnectionError: errors["base"] = ERROR_CANNOT_CONNECT except UnsupportedError: @@ -73,7 +73,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN): try: self.discovered_device = await validate_host(host) if self.discovered_device.server_only: - raise UnsupportedError + raise UnsupportedError # noqa: TRY301 except ConnectionError: return self.async_abort(reason=ERROR_CANNOT_CONNECT) except UnsupportedError: diff --git a/homeassistant/components/knx/config_flow.py b/homeassistant/components/knx/config_flow.py index 2fc1f49800c..7e4db1f889b 100644 --- a/homeassistant/components/knx/config_flow.py +++ b/homeassistant/components/knx/config_flow.py @@ -445,7 +445,7 @@ class KNXCommonFlow(ABC, ConfigEntryBaseFlow): try: key_bytes = bytes.fromhex(user_input[CONF_KNX_ROUTING_BACKBONE_KEY]) if len(key_bytes) != 16: - raise ValueError + raise ValueError # noqa: TRY301 except ValueError: errors[CONF_KNX_ROUTING_BACKBONE_KEY] = "invalid_backbone_key" if not errors: diff --git a/homeassistant/components/mailbox/__init__.py b/homeassistant/components/mailbox/__init__.py index b446ba3704e..e0438342a54 100644 --- a/homeassistant/components/mailbox/__init__.py +++ b/homeassistant/components/mailbox/__init__.py @@ -92,7 +92,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: platform.get_handler, hass, p_config, discovery_info ) else: - raise HomeAssistantError("Invalid mailbox platform.") + raise HomeAssistantError("Invalid mailbox platform.") # noqa: TRY301 if mailbox is None: _LOGGER.error("Failed to initialize mailbox platform %s", p_type) diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index 4a41f486831..e983f1b66f3 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -260,7 +260,7 @@ class MqttSensor(MqttEntity, RestoreSensor): return try: if (payload_datetime := dt_util.parse_datetime(payload)) is None: - raise ValueError + raise ValueError # noqa: TRY301 except ValueError: _LOGGER.warning("Invalid state message '%s' from '%s'", payload, msg.topic) self._attr_native_value = None @@ -280,7 +280,7 @@ class MqttSensor(MqttEntity, RestoreSensor): try: last_reset = dt_util.parse_datetime(str(payload)) if last_reset is None: - raise ValueError + raise ValueError # noqa: TRY301 self._attr_last_reset = last_reset except ValueError: _LOGGER.warning( diff --git a/homeassistant/components/notify/legacy.py b/homeassistant/components/notify/legacy.py index b3871d858e8..81444a36296 100644 --- a/homeassistant/components/notify/legacy.py +++ b/homeassistant/components/notify/legacy.py @@ -105,7 +105,7 @@ def async_setup_legacy( platform.get_service, hass, p_config, discovery_info ) else: - raise HomeAssistantError("Invalid notify platform.") + raise HomeAssistantError("Invalid notify platform.") # noqa: TRY301 if notify_service is None: # Platforms can decide not to create a service based diff --git a/homeassistant/components/python_script/__init__.py b/homeassistant/components/python_script/__init__.py index ab8cf17daa0..70e9c5b0d29 100644 --- a/homeassistant/components/python_script/__init__.py +++ b/homeassistant/components/python_script/__init__.py @@ -277,7 +277,7 @@ def execute(hass, filename, source, data=None, return_response=False): if not isinstance(restricted_globals["output"], dict): output_type = type(restricted_globals["output"]) restricted_globals["output"] = {} - raise ScriptError( + raise ScriptError( # noqa: TRY301 f"Expected `output` to be a dictionary, was {output_type}" ) except ScriptError as err: diff --git a/homeassistant/components/raincloud/__init__.py b/homeassistant/components/raincloud/__init__.py index e6f5d2ecf8d..a805024357c 100644 --- a/homeassistant/components/raincloud/__init__.py +++ b/homeassistant/components/raincloud/__init__.py @@ -102,7 +102,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool: try: raincloud = RainCloudy(username=username, password=password) if not raincloud.is_connected: - raise HTTPError + raise HTTPError # noqa: TRY301 hass.data[DATA_RAINCLOUD] = RainCloudHub(raincloud) except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex)) diff --git a/homeassistant/components/roborock/__init__.py b/homeassistant/components/roborock/__init__.py index 3743faa32d8..d107a0bee8b 100644 --- a/homeassistant/components/roborock/__init__.py +++ b/homeassistant/components/roborock/__init__.py @@ -174,7 +174,7 @@ async def setup_device_v1( if networking is None: # If the api does not return an error but does return None for # get_networking - then we need to go through cache checking. - raise RoborockException("Networking request returned None.") + raise RoborockException("Networking request returned None.") # noqa: TRY301 except RoborockException as err: _LOGGER.warning( "Not setting up %s because we could not get the network information of the device. " diff --git a/homeassistant/components/signal_messenger/notify.py b/homeassistant/components/signal_messenger/notify.py index 21d42f8912f..9321bc3232f 100644 --- a/homeassistant/components/signal_messenger/notify.py +++ b/homeassistant/components/signal_messenger/notify.py @@ -166,7 +166,7 @@ class SignalNotificationService(BaseNotificationService): and int(str(resp.headers.get("Content-Length"))) > attachment_size_limit ): - raise ValueError( + raise ValueError( # noqa: TRY301 "Attachment too large (Content-Length reports {}). Max size: {}" " bytes".format( int(str(resp.headers.get("Content-Length"))), @@ -179,7 +179,7 @@ class SignalNotificationService(BaseNotificationService): for chunk in resp.iter_content(1024): size += len(chunk) if size > attachment_size_limit: - raise ValueError( + raise ValueError( # noqa: TRY301 f"Attachment too large (Stream reports {size}). " f"Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes" ) diff --git a/homeassistant/components/starline/config_flow.py b/homeassistant/components/starline/config_flow.py index 6c38603a843..fbb7fa9acdc 100644 --- a/homeassistant/components/starline/config_flow.py +++ b/homeassistant/components/starline/config_flow.py @@ -214,7 +214,7 @@ class StarlineFlowHandler(ConfigFlow, domain=DOMAIN): self._captcha_image = data["captchaImg"] return self._async_form_auth_captcha(error) - raise Exception(data) # noqa: TRY002 + raise Exception(data) # noqa: TRY002, TRY301 except Exception as err: # noqa: BLE001 _LOGGER.error("Error auth user: %s", err) return self._async_form_auth_user(ERROR_AUTH_USER) diff --git a/homeassistant/components/tami4/config_flow.py b/homeassistant/components/tami4/config_flow.py index 0fa05bbebe4..72b19470f45 100644 --- a/homeassistant/components/tami4/config_flow.py +++ b/homeassistant/components/tami4/config_flow.py @@ -42,7 +42,7 @@ class Tami4ConfigFlow(ConfigFlow, domain=DOMAIN): if m := _PHONE_MATCHER.match(phone): self.phone = f"+972{m.group('number')}" else: - raise InvalidPhoneNumber + raise InvalidPhoneNumber # noqa: TRY301 await self.hass.async_add_executor_job( Tami4EdgeAPI.request_otp, self.phone ) diff --git a/homeassistant/components/template/vacuum.py b/homeassistant/components/template/vacuum.py index 9062f71d818..e512ce2eb04 100644 --- a/homeassistant/components/template/vacuum.py +++ b/homeassistant/components/template/vacuum.py @@ -318,7 +318,7 @@ class TemplateVacuum(TemplateEntity, StateVacuumEntity): try: battery_level_int = int(battery_level) if not 0 <= battery_level_int <= 100: - raise ValueError + raise ValueError # noqa: TRY301 except ValueError: _LOGGER.error( "Received invalid battery level: %s for entity %s. Expected: 0-100", diff --git a/homeassistant/components/websocket_api/connection.py b/homeassistant/components/websocket_api/connection.py index ef70df4a123..6c0c6f0c587 100644 --- a/homeassistant/components/websocket_api/connection.py +++ b/homeassistant/components/websocket_api/connection.py @@ -223,7 +223,7 @@ class ActiveConnection: try: if schema is False: if len(msg) > 2: - raise vol.Invalid("extra keys not allowed") + raise vol.Invalid("extra keys not allowed") # noqa: TRY301 handler(self.hass, self, msg) else: handler(self.hass, self, schema(msg)) diff --git a/homeassistant/components/websocket_api/http.py b/homeassistant/components/websocket_api/http.py index c65c4c65988..8ed3469d7ed 100644 --- a/homeassistant/components/websocket_api/http.py +++ b/homeassistant/components/websocket_api/http.py @@ -339,11 +339,11 @@ class WebSocketHandler: raise Disconnect from err if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING): - raise Disconnect + raise Disconnect # noqa: TRY301 if msg.type != WSMsgType.TEXT: disconnect_warn = "Received non-Text message." - raise Disconnect + raise Disconnect # noqa: TRY301 try: auth_msg_data = json_loads(msg.data) diff --git a/homeassistant/components/wyoming/data.py b/homeassistant/components/wyoming/data.py index e333a740741..1ee0f24f805 100644 --- a/homeassistant/components/wyoming/data.py +++ b/homeassistant/components/wyoming/data.py @@ -100,7 +100,7 @@ async def load_wyoming_info( while True: event = await client.read_event() if event is None: - raise WyomingError( + raise WyomingError( # noqa: TRY301 "Connection closed unexpectedly", ) diff --git a/pyproject.toml b/pyproject.toml index e94c9e96225..1cccc155d34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -821,8 +821,7 @@ ignore = [ "PLE0605", # temporarily disabled - "RET503", - "TRY301" + "RET503" ] [tool.ruff.lint.flake8-import-conventions.extend-aliases] diff --git a/tests/components/system_log/test_init.py b/tests/components/system_log/test_init.py index 1f1c4464c71..83adab8200b 100644 --- a/tests/components/system_log/test_init.py +++ b/tests/components/system_log/test_init.py @@ -36,7 +36,7 @@ async def get_error_log(hass_ws_client): def _generate_and_log_exception(exception, log): try: - raise Exception(exception) # noqa: TRY002 + raise Exception(exception) # noqa: TRY002, TRY301 except Exception: _LOGGER.exception(log) @@ -461,7 +461,7 @@ async def test__figure_out_source(hass: HomeAssistant) -> None: in a test because the test is not a component. """ try: - raise ValueError("test") + raise ValueError("test") # noqa: TRY301 except ValueError as ex: exc_info = (type(ex), ex, ex.__traceback__) mock_record = MagicMock( @@ -486,7 +486,7 @@ async def test__figure_out_source(hass: HomeAssistant) -> None: async def test_formatting_exception(hass: HomeAssistant) -> None: """Test that exceptions are formatted correctly.""" try: - raise ValueError("test") + raise ValueError("test") # noqa: TRY301 except ValueError as ex: exc_info = (type(ex), ex, ex.__traceback__) mock_record = MagicMock(