mirror of
https://github.com/home-assistant/core.git
synced 2025-11-08 10:29:27 +00:00
Generate HomeAssistantError message from English translations (#113305)
* Fetch exception message from translation cache * Improve tests * Return translation key without path, cleanup * Fetch translations when string variant is requested * Move import * revert changes ConfigValidationError * mypy * Remove _str__ method instead * Type _message for mqtt template exception classes * Revert changes made to test_config.py * Undo changes TemplateError * Follow up comments and test coverage
This commit is contained in:
@@ -13,6 +13,9 @@ if TYPE_CHECKING:
|
||||
class HomeAssistantError(Exception):
|
||||
"""General Home Assistant exception occurred."""
|
||||
|
||||
_message: str | None = None
|
||||
generate_message: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args: object,
|
||||
@@ -21,11 +24,42 @@ class HomeAssistantError(Exception):
|
||||
translation_placeholders: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
"""Initialize exception."""
|
||||
if not args and translation_key and translation_domain:
|
||||
self.generate_message = True
|
||||
args = (translation_key,)
|
||||
|
||||
super().__init__(*args)
|
||||
self.translation_domain = translation_domain
|
||||
self.translation_key = translation_key
|
||||
self.translation_placeholders = translation_placeholders
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Return exception message.
|
||||
|
||||
If no message was passed to `__init__`, the exception message is generated from
|
||||
the translation_key. The message will be in English, regardless of the configured
|
||||
language.
|
||||
"""
|
||||
|
||||
if self._message:
|
||||
return self._message
|
||||
|
||||
if not self.generate_message:
|
||||
self._message = super().__str__()
|
||||
return self._message
|
||||
|
||||
if TYPE_CHECKING:
|
||||
assert self.translation_key is not None
|
||||
assert self.translation_domain is not None
|
||||
|
||||
# pylint: disable-next=import-outside-toplevel
|
||||
from .helpers.translation import async_get_exception_message
|
||||
|
||||
self._message = async_get_exception_message(
|
||||
self.translation_domain, self.translation_key, self.translation_placeholders
|
||||
)
|
||||
return self._message
|
||||
|
||||
|
||||
class ConfigValidationError(HomeAssistantError, ExceptionGroup[Exception]):
|
||||
"""A validation exception occurred when validating the configuration."""
|
||||
@@ -47,10 +81,6 @@ class ConfigValidationError(HomeAssistantError, ExceptionGroup[Exception]):
|
||||
)
|
||||
self._message = message
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Return exception message string."""
|
||||
return self._message
|
||||
|
||||
|
||||
class ServiceValidationError(HomeAssistantError):
|
||||
"""A validation exception occurred when calling a service."""
|
||||
|
||||
Reference in New Issue
Block a user