我是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>`
答案 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块照常进行处理。