繁体   English   中英

如何将 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 异常模块并在异常中记录实际消息。

在可能引发两个异常的情况下, 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 核心异常模块?
  • 这种模式的一个例子会非常有帮助。

异常将按照“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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM