gpt4 book ai didi

python - 如何将 Azure Python SDK 异常添加到 try/except 语句?

转载 作者:行者123 更新时间:2023-12-05 09:07:41 26 4
gpt4 key购买 nike

我是 Python 新手。我有一个可以工作的整体 Python 程序,我正在将其分解为单独的 Python 函数。我想使用 try: - except: 模式来捕获每个函数的特定异常。

示例:创建 Key Vault 客户端并从 Key Vault 检索 secret

import logging
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import 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

kv_client = create_kv_client('mykeyvaultname', credentials)


def retrieve_secret(table_stg_acct_key, kv_client):
retrieved_account_key = kv_client.get_secret(table_stg_acct_key)
return retrieved_account_key

try:
retrieved_account_key = retrieve_secret('mykeyvaultsecretname', kv_client)
print(retrieved_account_key)
except:
logging.error('####### Failed to retrieve key from Key Vault #######')
raise BaseException

我不想在这里使用 raise BaseException,而是使用 Azure Core exceptions module并在异常中记录实际消息。

在可能引发两个异常的情况下,如何处理 except: 语句?

示例:get_secret 方法可能会引发两个异常。

ServiceRequestError: <urllib3.connection.HTTPSConnection object at 0x000001BFA2299640>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
ResourceNotFoundError: (SecretNotFound) A secret with (name/id) notmykeyvaultsecretname was not found in this key vault. If you recently deleted this secret you may be able to recover it using the correct recovery command. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125182

这是如何实现的?

  • 我必须导入 azure core 异常模块吗?
  • 此模式的示例会非常有帮助。

最佳答案

异常将按照“except”子句的顺序捕获,但要注意子类树,因为 except 也会捕获所有子类。例如,这会导致代码无法访问。

try:
# do something
except BaseException:
# do something with
except DerivedException:
# assuming DerivedException is an extension of BaseException, you can't reach that code

所以先把它们放在最具体的位置。

在您的 Azure 情况下,这会导致以下情况:

from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ServiceRequestError,
ResourceNotFoundError,
AzureError
)

try:
# do KV stuff
except ClientAuthenticationError as e:
# Can occur if either tenant_id, client_id or client_secret is incorrect
logger.critical("Azure SDK was not able to connect to Key Vault", e)
except HttpResponseError as e:
# One reason is when Key Vault Name is incorrect
logger.critical("Possible wrong Vault name given", e)
except ServiceRequestError:
# Network error, I will let it raise to higher level
raise
except ResourceNotFoundError:
# Let's assume it's not big deal here, just let it go
pass
except AzureError as e:
# Will catch everything that is from Azure SDK, but not the two previous
logger.critical("Azure SDK was not able to deal with my query", e)
raise
except Exception as e:
# Anything else that is not Azure related (network, stdlib, etc.)
logger.critical("Unknown error I can't blame Azure for", e)
raise

关于python - 如何将 Azure Python SDK 异常添加到 try/except 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64613699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com