Rename ex to exc as name for exceptions (#104479)

pull/104498/head
Jan Bouwhuis 2023-11-25 08:30:18 +01:00 committed by GitHub
parent b94c9c8f6d
commit 487ff8cd7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 43 deletions

View File

@ -442,15 +442,15 @@ async def async_hass_config_yaml(hass: HomeAssistant) -> dict:
hass.config.path(YAML_CONFIG_FILE), hass.config.path(YAML_CONFIG_FILE),
secrets, secrets,
) )
except HomeAssistantError as ex: except HomeAssistantError as exc:
if not (base_ex := ex.__cause__) or not isinstance(base_ex, MarkedYAMLError): if not (base_exc := exc.__cause__) or not isinstance(base_exc, MarkedYAMLError):
raise raise
# Rewrite path to offending YAML file to be relative the hass config dir # Rewrite path to offending YAML file to be relative the hass config dir
if base_ex.context_mark and base_ex.context_mark.name: if base_exc.context_mark and base_exc.context_mark.name:
base_ex.context_mark.name = _relpath(hass, base_ex.context_mark.name) base_exc.context_mark.name = _relpath(hass, base_exc.context_mark.name)
if base_ex.problem_mark and base_ex.problem_mark.name: if base_exc.problem_mark and base_exc.problem_mark.name:
base_ex.problem_mark.name = _relpath(hass, base_ex.problem_mark.name) base_exc.problem_mark.name = _relpath(hass, base_exc.problem_mark.name)
raise raise
core_config = config.get(CONF_CORE, {}) core_config = config.get(CONF_CORE, {})
@ -541,32 +541,32 @@ def process_ha_config_upgrade(hass: HomeAssistant) -> None:
@callback @callback
def async_log_schema_error( def async_log_schema_error(
ex: vol.Invalid, exc: vol.Invalid,
domain: str, domain: str,
config: dict, config: dict,
hass: HomeAssistant, hass: HomeAssistant,
link: str | None = None, link: str | None = None,
) -> None: ) -> None:
"""Log a schema validation error.""" """Log a schema validation error."""
message = format_schema_error(hass, ex, domain, config, link) message = format_schema_error(hass, exc, domain, config, link)
_LOGGER.error(message) _LOGGER.error(message)
@callback @callback
def async_log_config_validator_error( def async_log_config_validator_error(
ex: vol.Invalid | HomeAssistantError, exc: vol.Invalid | HomeAssistantError,
domain: str, domain: str,
config: dict, config: dict,
hass: HomeAssistant, hass: HomeAssistant,
link: str | None = None, link: str | None = None,
) -> None: ) -> None:
"""Log an error from a custom config validator.""" """Log an error from a custom config validator."""
if isinstance(ex, vol.Invalid): if isinstance(exc, vol.Invalid):
async_log_schema_error(ex, domain, config, hass, link) async_log_schema_error(exc, domain, config, hass, link)
return return
message = format_homeassistant_error(hass, ex, domain, config, link) message = format_homeassistant_error(hass, exc, domain, config, link)
_LOGGER.error(message, exc_info=ex) _LOGGER.error(message, exc_info=exc)
def _get_annotation(item: Any) -> tuple[str, int | str] | None: def _get_annotation(item: Any) -> tuple[str, int | str] | None:
@ -647,7 +647,7 @@ def _relpath(hass: HomeAssistant, path: str) -> str:
def stringify_invalid( def stringify_invalid(
hass: HomeAssistant, hass: HomeAssistant,
ex: vol.Invalid, exc: vol.Invalid,
domain: str, domain: str,
config: dict, config: dict,
link: str | None, link: str | None,
@ -668,26 +668,26 @@ def stringify_invalid(
message_suffix = f", please check the docs at {link}" message_suffix = f", please check the docs at {link}"
else: else:
message_suffix = "" message_suffix = ""
if annotation := find_annotation(config, ex.path): if annotation := find_annotation(config, exc.path):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}" message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
path = "->".join(str(m) for m in ex.path) path = "->".join(str(m) for m in exc.path)
if ex.error_message == "extra keys not allowed": if exc.error_message == "extra keys not allowed":
return ( return (
f"{message_prefix}: '{ex.path[-1]}' is an invalid option for '{domain}', " f"{message_prefix}: '{exc.path[-1]}' is an invalid option for '{domain}', "
f"check: {path}{message_suffix}" f"check: {path}{message_suffix}"
) )
if ex.error_message == "required key not provided": if exc.error_message == "required key not provided":
return ( return (
f"{message_prefix}: required key '{ex.path[-1]}' not provided" f"{message_prefix}: required key '{exc.path[-1]}' not provided"
f"{message_suffix}" f"{message_suffix}"
) )
# This function is an alternative to the stringification done by # This function is an alternative to the stringification done by
# vol.Invalid.__str__, so we need to call Exception.__str__ here # vol.Invalid.__str__, so we need to call Exception.__str__ here
# instead of str(ex) # instead of str(exc)
output = Exception.__str__(ex) output = Exception.__str__(exc)
if error_type := ex.error_type: if error_type := exc.error_type:
output += " for " + error_type output += " for " + error_type
offending_item_summary = repr(_get_by_path(config, ex.path)) offending_item_summary = repr(_get_by_path(config, exc.path))
if len(offending_item_summary) > max_sub_error_length: if len(offending_item_summary) > max_sub_error_length:
offending_item_summary = ( offending_item_summary = (
f"{offending_item_summary[: max_sub_error_length - 3]}..." f"{offending_item_summary[: max_sub_error_length - 3]}..."
@ -728,7 +728,7 @@ def humanize_error(
@callback @callback
def format_homeassistant_error( def format_homeassistant_error(
hass: HomeAssistant, hass: HomeAssistant,
ex: HomeAssistantError, exc: HomeAssistantError,
domain: str, domain: str,
config: dict, config: dict,
link: str | None = None, link: str | None = None,
@ -739,7 +739,7 @@ def format_homeassistant_error(
# offending configuration key, use the domain key as path instead. # offending configuration key, use the domain key as path instead.
if annotation := find_annotation(config, [domain]): if annotation := find_annotation(config, [domain]):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}" message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
message = f"{message_prefix}: {str(ex) or repr(ex)}" message = f"{message_prefix}: {str(exc) or repr(exc)}"
if domain != CONF_CORE and link: if domain != CONF_CORE and link:
message += f", please check the docs at {link}" message += f", please check the docs at {link}"
@ -749,13 +749,13 @@ def format_homeassistant_error(
@callback @callback
def format_schema_error( def format_schema_error(
hass: HomeAssistant, hass: HomeAssistant,
ex: vol.Invalid, exc: vol.Invalid,
domain: str, domain: str,
config: dict, config: dict,
link: str | None = None, link: str | None = None,
) -> str: ) -> str:
"""Format configuration validation error.""" """Format configuration validation error."""
return humanize_error(hass, ex, domain, config, link) return humanize_error(hass, exc, domain, config, link)
async def async_process_ha_core_config(hass: HomeAssistant, config: dict) -> None: async def async_process_ha_core_config(hass: HomeAssistant, config: dict) -> None:
@ -981,17 +981,17 @@ async def merge_packages_config(
hass, domain hass, domain
) )
component = integration.get_component() component = integration.get_component()
except LOAD_EXCEPTIONS as ex: except LOAD_EXCEPTIONS as exc:
_log_pkg_error( _log_pkg_error(
hass, hass,
pack_name, pack_name,
comp_name, comp_name,
config, config,
f"Integration {comp_name} caused error: {str(ex)}", f"Integration {comp_name} caused error: {str(exc)}",
) )
continue continue
except INTEGRATION_LOAD_EXCEPTIONS as ex: except INTEGRATION_LOAD_EXCEPTIONS as exc:
_log_pkg_error(hass, pack_name, comp_name, config, str(ex)) _log_pkg_error(hass, pack_name, comp_name, config, str(exc))
continue continue
try: try:

View File

@ -406,8 +406,8 @@ class ConfigEntry:
"%s.async_setup_entry did not return boolean", integration.domain "%s.async_setup_entry did not return boolean", integration.domain
) )
result = False result = False
except ConfigEntryError as ex: except ConfigEntryError as exc:
error_reason = str(ex) or "Unknown fatal config entry error" error_reason = str(exc) or "Unknown fatal config entry error"
_LOGGER.exception( _LOGGER.exception(
"Error setting up entry %s for %s: %s", "Error setting up entry %s for %s: %s",
self.title, self.title,
@ -416,8 +416,8 @@ class ConfigEntry:
) )
await self._async_process_on_unload(hass) await self._async_process_on_unload(hass)
result = False result = False
except ConfigEntryAuthFailed as ex: except ConfigEntryAuthFailed as exc:
message = str(ex) message = str(exc)
auth_base_message = "could not authenticate" auth_base_message = "could not authenticate"
error_reason = message or auth_base_message error_reason = message or auth_base_message
auth_message = ( auth_message = (
@ -432,13 +432,13 @@ class ConfigEntry:
await self._async_process_on_unload(hass) await self._async_process_on_unload(hass)
self.async_start_reauth(hass) self.async_start_reauth(hass)
result = False result = False
except ConfigEntryNotReady as ex: except ConfigEntryNotReady as exc:
self._async_set_state(hass, ConfigEntryState.SETUP_RETRY, str(ex) or None) self._async_set_state(hass, ConfigEntryState.SETUP_RETRY, str(exc) or None)
wait_time = 2 ** min(self._tries, 4) * 5 + ( wait_time = 2 ** min(self._tries, 4) * 5 + (
randint(RANDOM_MICROSECOND_MIN, RANDOM_MICROSECOND_MAX) / 1000000 randint(RANDOM_MICROSECOND_MIN, RANDOM_MICROSECOND_MAX) / 1000000
) )
self._tries += 1 self._tries += 1
message = str(ex) message = str(exc)
ready_message = f"ready yet: {message}" if message else "ready yet" ready_message = f"ready yet: {message}" if message else "ready yet"
_LOGGER.debug( _LOGGER.debug(
( (
@ -565,13 +565,13 @@ class ConfigEntry:
await self._async_process_on_unload(hass) await self._async_process_on_unload(hass)
return result return result
except Exception as ex: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception( _LOGGER.exception(
"Error unloading entry %s for %s", self.title, integration.domain "Error unloading entry %s for %s", self.title, integration.domain
) )
if integration.domain == self.domain: if integration.domain == self.domain:
self._async_set_state( self._async_set_state(
hass, ConfigEntryState.FAILED_UNLOAD, str(ex) or "Unknown error" hass, ConfigEntryState.FAILED_UNLOAD, str(exc) or "Unknown error"
) )
return False return False

View File

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