For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /developers/core/integration-quality-scale/rules/test-before-setup.md.

在集成初始化时检查是否能够正确设置

import RelatedRules from './_includes/related_rules.jsx'

原因

初始化集成时,我们应该检查是否能够正确设置。 这样可以立即让用户知道集成无法正常工作。

实现这些检查可以提高集成正确工作的信心,并以用户友好的方式展示错误。 这将改善用户体验。

示例实现

当失败的原因是临时性的(例如设备暂时离线),我们应该抛出 ConfigEntryNotReady,Home Assistant 稍后会重试设置。 如果失败的原因是密码不正确或 api key 无效,我们应该抛出 ConfigEntryAuthFailed,Home Assistant 会提示用户重新进行身份验证(如果已实现重新身份验证流程)。 如果我们预计集成在可预见的将来无法工作,我们应该抛出 ConfigEntryError

__init__.py:

async def async_setup_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
    """Set up my integration from a config entry."""

    client = MyClient(entry.data[CONF_HOST])

    try:
        await client.async_setup()
    except OfflineException as ex:
        raise ConfigEntryNotReady("Device is offline") from ex
    except InvalidAuthException as ex:
        raise ConfigEntryAuthFailed("Invalid authentication") from ex
    except AccountClosedException as ex:
        raise ConfigEntryError("Account closed") from ex

    entry.runtime_data = client

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True
Info

请注意,使用 data update coordinator 并通过 await coordinator.async_config_entry_first_refresh() 时,也可能隐式实现此功能。

更多资源

关于配置条目及其生命周期的更多信息,请参见config entry 文档

例外

本规则没有例外。

相关规则