如何将 Azure Python SDK 异常添加到 try/except 语句?
How to add Azure Python SDK exceptions to try/except statements?
我是 Python 的新手。我有一个工作的、整体的 Python 程序,我正在分解成单独的 Python 函数。我想使用 try:
- except:
模式来捕获每个函数的特定异常。
示例: 创建 Key Vault 客户端并从 Key Vault 中检索机密
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
方法可能引发两个异常。
- 如果 Key Vault URL 不正确,则会引发
ServiceRequestError
:
ServiceRequestError: <urllib3.connection.HTTPSConnection object at 0x000001BFA2299640>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
- 如果 Key Vault 机密名称不正确,则会引发 ResourceNotFoundError:
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 核心异常模块?
- 这个模式的例子会很有帮助。
异常将按照“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:
# 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:
# 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 的新手。我有一个工作的、整体的 Python 程序,我正在分解成单独的 Python 函数。我想使用 try:
- except:
模式来捕获每个函数的特定异常。
示例: 创建 Key Vault 客户端并从 Key Vault 中检索机密
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
方法可能引发两个异常。
- 如果 Key Vault URL 不正确,则会引发
ServiceRequestError
:
ServiceRequestError: <urllib3.connection.HTTPSConnection object at 0x000001BFA2299640>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
- 如果 Key Vault 机密名称不正确,则会引发 ResourceNotFoundError:
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 核心异常模块?
- 这个模式的例子会很有帮助。
异常将按照“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:
# 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:
# 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