Como adicionar exceções do SDK do Python do Azure para tentar / exceto instruções?

Oct 31 2020

Sou novo em Python. Eu tenho um programa Python monolítico funcional que estou dividindo em funções Python individuais. Eu gostaria de usar o padrão try:- except:para capturar exceções específicas para cada função.

Exemplo: crie um cliente Key Vault e recupere um segredo do 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

Em vez de raise BaseExceptionaqui, gostaria de usar o módulo de exceções do Azure Core e registrar a mensagem real na exceção.

Como a except:instrução é tratada no caso em que duas exceções podem ser levantadas?

Exemplo: pode haver duas exceções levantadas pelo get_secretmétodo.

  • Se o URL do Key Vault estiver incorreto, um ServiceRequestErroré gerado:
ServiceRequestError: <urllib3.connection.HTTPSConnection object at 0x000001BFA2299640>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
  • Se o nome do segredo do Key Vault estiver incorreto, um ResourceNotFoundError será gerado:
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

Como isso é feito?

  • Tenho que importar o módulo de exceção do núcleo azure?
  • Um exemplo desse padrão seria muito útil.

Respostas

2 LaurentMazuel Oct 31 2020 at 04:28

A exceção será capturada na ordem das cláusulas "exceto", mas cuidado com a árvore da subclasse, uma vez que uma exceção capturará todas as subclasses também. Por exemplo, este leva a um código inacessível.

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

Portanto, coloque-os primeiro nos mais específicos.

Em sua situação do Azure, isso traz algo como:

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

try:
    # do KV stuff
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