如何捕获Key Vault SecretClient错误Azure Python SDK?

时间:2020-10-29 22:23:26

标签: python azure-keyvault try-except azure-sdk-python

我是Python的新手。我有一个可运行的整体程序,我想使用def-try:来处理错误,将其分解为单个功能(except:)。

在创建密钥保险库SecretClient时,有哪些方法可以捕获错误?

尝试1:

  • 当我放错kv_name时,这里什么也没发生。
  • 我希望它记录指定的except:消息。
credentials = DefaultAzureCredential()

def create_kv_client(kv_name, credentials):
    try:
        kv_uri = 'https://' + kv_name + '.vault.azure.net'
        kv_client = SecretClient(vault_url=kv_uri, credential=credentials)
    except:
        logging.error('####### Failed to create Key Vault Client #######')
    return kv_client

kv_client = create_kv_client('notmykeyvaultname', credentials)

尝试2:

  • 当我放错了kv_name时,这里什么也没有发生
  • 我希望它会引发错误。
credentials = DefaultAzureCredential()

def create_kv_client(kv_name, credentials):
    try:
        kv_uri = 'https://' + kv_name + '.vault.azure.net'
        kv_client = SecretClient(vault_url=kv_uri, credential=credentials)
    except:
        logging.error('####### Failed to create Key Vault Client #######')
    return kv_client

kv_client = create_kv_client('notmykeyvaultname', credentials)

if kv_client == None:
    raise Exception('Failed to create Key Vault Client')

尝试3:

  • try:-except:移动到函数调用也未触发日志记录消息
  • 我希望SecretClient在这里失败!?
credentials = DefaultAzureCredential()

def create_kv_client(kv_name, credentials):
    kv_uri = 'https://' + kv_name + '.vault.azure.net'
    kv_client = SecretClient(vault_url=kv_uri, credential=credentials)
    return kv_client

try:
    kv_client = create_kv_client('notmykeyvaultname', credentials)
except:
    logging.info('####### Failed to create Key Vault client #######')

完整性检查:

  • 当我在函数的外部 中运行命令时,失败的SecretClient的输出不是None
  • 我可以在这里确定SecretClient是否已成功创建吗?
credentials = DefaultAzureCredential()

kv_uri = 'https://' + 'notmykeyvaultname' + '.vault.azure.net'

kv_client = SecretClient(vault_url=kv_uri, credential=credentials)

kv_client

`<azure.keyvault.secrets._client.SecretClient at 0x1512046b370>`

1 个答案:

答案 0 :(得分:1)

构造函数不会检查给定的文件库是否存在,或者您是否可以访问它,因此,在尝试中,它会成功:您获得了SecretClient实例,没有引发错误。

如果URL是不存在的保管库的URL,或者您无权访问的保管库,则在您首次尝试操作时会看到错误消息:

>>> vault_url = "https://nonexistentvaultdoesnotexist.vault.azure.net"
>>> client = SecretClient(vault_url, DefaultAzureCredential())
>>> client.get_secret('secret_name')
Traceback (most recent call last):
...
azure.core.exceptions.ServiceRequestError: <urllib3.connection.VerifiedHTTPSConnection object at 0x000001E313946198>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

失败的操作会引发azure-core中定义的错误,您可以使用try / except块照常进行处理。