Home Assistant Exception Types: A Complete Guide to Error Handling in Core
Home Assistant defines a comprehensive hierarchy of exception types in homeassistant/exceptions.py, with HomeAssistantError serving as the base class for all core errors, including validation failures like ConfigValidationError, integration setup errors like ConfigEntryNotReady, and authentication errors like ConfigEntryAuthFailed.
The home-assistant/core repository implements a structured exception hierarchy to standardize error handling across the platform. Understanding these Home Assistant exception types is essential for integration developers and core contributors who need to raise meaningful errors or handle failures gracefully while leveraging the framework's built-in retry and translation capabilities.
Core Exception Hierarchy in Home Assistant
All core-level exceptions inherit from HomeAssistantError, defined in homeassistant/exceptions.py. This base class provides optional translation support, allowing exception messages to render in the UI without requiring specific locale handling.
Base Class: HomeAssistantError
HomeAssistantError acts as the root for all custom Home Assistant errors. When catching application-level failures, developers can use except HomeAssistantError to handle any core or integration-specific exception gracefully while maintaining access to translatable error messages.
Validation and Configuration Errors
Home Assistant separates validation failures into distinct exception types based on context:
- ConfigValidationError: Raised during
configuration.yamlparsing. Inherits fromExceptionGroupto bundle multiple validation failures. - ServiceValidationError: Raised when service calls contain invalid data.
- InvalidEntityFormatError: Raised when entity IDs lack proper domain formatting.
- NoEntitySpecifiedError: Raised when services or automations expect an entity but receive none.
- TemplateError: Raised during Jinja2 template rendering failures.
- ConditionError: Abstract base for automation condition-evaluation errors, with concrete subclasses
ConditionErrorMessage,ConditionErrorIndex, andConditionErrorContainer.
Integration and Platform Errors
Integration developers use these exceptions to communicate setup and runtime failures:
- IntegrationError: Generic wrapper for platform or config-entry failures.
- PlatformNotReady: Signals that a platform cannot start because an external device is unavailable. Triggers automatic retry logic.
- ConfigEntryError: General failure while setting up a config entry.
- ConfigEntryNotReady: Config entry cannot be set up yet, typically when waiting for a device to come online.
- ConfigEntryAuthFailed: Authentication with an external service failed, triggering a reconfiguration flow.
- InvalidStateError: An unexpected internal state was encountered.
Authentication and Authorization Errors
Security-related exceptions handle permission and identity failures:
- Unauthorized: Action performed without sufficient permissions. Requires
context,user_id, andentity_idparameters. - UnknownUser: The supplied user ID does not exist in the system.
- OAuth2TokenRequestError: Base for OAuth 2.0 token refresh problems, inheriting from
aiohttp.ClientResponseError. - OAuth2TokenRequestTransientError: Temporary refresh failure indicating a retry should occur later.
- OAuth2TokenRequestReauthError: Permanent failure requiring user re-authentication.
Service and Utility Errors
Common runtime exceptions include:
- ServiceNotFound: Requested service does not exist in the specified domain.
- ServiceNotSupported: Service exists but the target entity cannot handle it.
- MaxLengthExceeded: String value exceeds configured maximum length.
- DependencyError: Python package dependencies could not be installed.
Component-Specific Exception Types
Beyond the core hierarchy, individual integrations define domain-specific exceptions that inherit from HomeAssistantError. These allow precise error handling while maintaining compatibility with generic except HomeAssistantError clauses.
Notable component exception files include:
homeassistant/components/sonos/exception.py: DefinesSonosUpdateErrorfor speaker communication failures.homeassistant/components/media_source/error.py: ContainsMediaSourceErrorfor media browsing and playback issues.homeassistant/components/stream/exceptions.py: IncludesStreamOpenClientError,StreamWorkerError, andStreamEndedErrorfor video stream handling.homeassistant/components/proxmoxve/config_flow.py: DefinesProxmoxErrorandProxmoxSSLErrorfor Proxmox virtualization errors.homeassistant/components/python_script/__init__.py: ContainsScriptErrorfor Python script execution failures.
Additional helper modules define specialized exceptions:
homeassistant/helpers/config_entry_oauth2_flow.py:ImplementationUnavailableErrorhomeassistant/helpers/intent.py:IntentError,IntentHandleError,MatchFailedErrorhomeassistant/helpers/device_registry.py:DeviceInfoError,DeviceCollisionErrorhomeassistant/helpers/aiohttp_client.py:SSRFRedirectErrorfor network security checks
Practical Examples: Using Home Assistant Exceptions
The following patterns demonstrate how to raise and handle Home Assistant exception types effectively in integrations and custom components.
Raising Core Exceptions
When validating service calls or configuration data, raise specific exceptions to provide clear feedback:
from homeassistant.exceptions import ServiceNotFound, ServiceValidationError
def call_service(hass, domain, service, data):
"""Call a Home Assistant service with proper error handling."""
if not hass.services.has_service(domain, service):
raise ServiceNotFound(domain, service)
if not validate_data(data):
raise ServiceValidationError("Invalid service data provided")
hass.services.async_call(domain, service, data)
Handling Integration Setup Errors
Config entries should use specific exception types to trigger appropriate retry or reauthentication flows:
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestReauthError,
)
async def async_setup_entry(hass, entry):
"""Set up a config entry with robust error handling."""
try:
await my_integration.async_initialize(entry)
except ConfigEntryAuthFailed:
# Trigger reconfiguration flow
hass.components.persistent_notification.async_create(
"Authentication failed – please re-configure the integration."
)
return False
except ConfigEntryNotReady:
# Signal retry later
raise ConfigEntryNotReady from None
except OAuth2TokenRequestReauthError as exc:
# Force token refresh flow
await hass.config_entries.async_reload(entry.entry_id)
raise
return True
Catch-All Error Handling
For generic error logging or UI notification, catch the base HomeAssistantError:
from homeassistant.exceptions import HomeAssistantError
def safe_operation():
try:
# Code that may raise any HA-specific exception
do_something()
except HomeAssistantError as err:
_LOGGER.error("Home Assistant error: %s", err)
# Error message supports UI translation
Validating Automation Conditions
Use condition-specific errors when building automation engines or validation tools:
from homeassistant.exceptions import ConditionErrorMessage
def validate_condition(condition_type, payload):
"""Validate automation condition payload."""
if not payload:
raise ConditionErrorMessage(
type=condition_type,
message="Payload is empty"
)
Summary
Home Assistant implements a comprehensive exception hierarchy to standardize error handling across its core framework and integrations:
- Base Class:
HomeAssistantErrorserves as the root for all custom errors, providing translation support for UI rendering. - Validation Errors:
ConfigValidationError,ServiceValidationError, andTemplateErrorhandle configuration and service call failures. - Integration Errors:
ConfigEntryNotReady,ConfigEntryAuthFailed, andPlatformNotReadymanage setup states and retry logic. - Security Errors:
Unauthorized,UnknownUser, and OAuth2-specific exceptions handle authentication and permission failures. - Component Extensions: Individual integrations inherit from
HomeAssistantErrorto create domain-specific exceptions while maintaining compatibility with generic error handlers.
Frequently Asked Questions
What is the base exception class in Home Assistant?
HomeAssistantError is the base class for all custom exceptions in Home Assistant, defined in homeassistant/exceptions.py. All core and integration-specific exceptions inherit from this class, allowing developers to catch any Home Assistant-specific error with a single except HomeAssistantError clause while supporting UI translation of error messages.
How do I handle configuration entry setup failures in my integration?
Use specific exception types from homeassistant/exceptions.py to signal different failure modes. Raise ConfigEntryNotReady when a device is temporarily unavailable to trigger automatic retry logic. Raise ConfigEntryAuthFailed when authentication fails to prompt the user for reconfiguration. These exceptions integrate with Home Assistant's config entry management system to provide appropriate UI feedback and recovery flows.
What is the difference between ServiceNotFound and ServiceNotSupported?
ServiceNotFound indicates that the requested service does not exist within the specified domain—typically a typo or missing integration. ServiceNotSupported indicates that the service exists but the specific target entity cannot handle that service call, often due to entity capabilities or state limitations. Both inherit from HomeAssistantError and are defined in homeassistant/exceptions.py.
Can I create custom exceptions for my Home Assistant integration?
Yes, you should create custom exceptions by inheriting from HomeAssistantError (imported from homeassistant.exceptions). This ensures your integration's errors can be caught alongside core exceptions while allowing domain-specific error handling. Place your exception definitions in a dedicated exception.py file within your component directory, following the pattern used by components like sonos, media_source, and stream.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →