Azure KeyVault GetSecretAsync.Result.Value 错误处理

Azure KeyVault GetSecretAsync.Result.Value error handling

我有以下代码行 return 来自 KeyVault

的秘密
string kvSecret = kVClient.GetSecretAsync(azureKeyVaultUrl, secret).Result.Value;

虽然这按预期工作,但我不太清楚 Result.Value 同步执行如何处理运行时错误、异常等。

我试图了解当我调用 Result.Value 时是否有任何可能出现错误并且值 returned 实际上不是秘密而是一些随机错误因此我的变量 kvSecret 不包含正确的值,而是包含其他内容。

我问这个问题的原因是我想确保如果变量不为 null 或空,它将始终包含秘密而不是其他随机字符串。

不幸的是,KeyVault 客户端被设计为 return 带有 KeyVaultErrorException 的任务,以防秘密不存在而不是失败 message\result。

在您的情况下,它会爆炸,因为当您调用 .Result 时,它会解包任务中的异常并将中断执行流程。

在 KeyVault 中检索机密的最佳方法是将逻辑包装在 Try\Catch 块中,如下所示:

try
{
    var secret = await client.GetSecretAsync(secretPath);
    //... any other logic here ...
}
catch (KeyVaultErrorException kvex)
{
    //handle key not found here
}
catch (HttpRequestException ex)
{
    //handle any other error here if needed
}

为了更容易使用 keyvault,我通常会创建一个 class 来处理这些逻辑,例如:

public class SecretManager
{
    KeyVaultClient client;
    public SecretManager(KeyVaultClient client){ this.client = client; }

    public Task<string> GetSecretAsync(string secretName){
        //here I wrap the logic mentioned above
    }
}

.

The above snipped is from the top of my head, not a copy from production code

如果您使用上述逻辑,而不是针对未找到的秘密抛出异常,而是进行适当的异常处理和 return 空值或代表未找到秘密的值,那么您将能够像预期的那样打开结果。