如何在Azure Python SDK中捕获429限流异常?
如何在Azure Python SDK中捕获429限流异常?
你的问题源于Azure Python SDK默认启用了自动重试策略:当收到429限流响应时,SDK会根据响应头的Retry-After值自动等待并重试请求,不会立即抛出HttpResponseError——这是设计的默认行为,目的是减少开发者手动处理重试的工作量。而404这类非重试类错误会直接抛出异常,因此你会看到两种错误的表现差异。
解决方法
方法1:自定义重试策略,控制重试行为
你可以通过azure.core.pipeline.policies.RetryPolicy自定义重试规则,比如限制重试次数,当超过重试次数后,SDK就会抛出429对应的异常。
示例代码:
from azure.mgmt.storage import StorageManagementClient from azure.core import exceptions from azure.core.pipeline.policies import RetryPolicy # 自定义重试策略:最多重试2次,超过后抛出异常 retry_policy = RetryPolicy(max_retries=2) storage_client = StorageManagementClient( credential="tokenCredential", subscription_id="subscriptionId", retry_policy=retry_policy ) while True: try: account_properties = storage_client.storage_accounts.get_properties( account_name="myStorageAccount", resource_group_name="myResourceGroup" ) print(account_properties) except exceptions.HttpResponseError as httpErr: if httpErr.status_code == 429: print("###捕获到429限流异常###") print(f"错误信息: {httpErr.message}") print(f"建议重试等待时间: {httpErr.response.headers.get('Retry-After')}秒") else: print(f"###捕获到其他HTTP异常###") print(httpErr.message) break
方法2:完全禁用自动重试
如果你希望直接捕获429异常而不进行任何自动重试,可以将重试策略的max_retries设为0:
from azure.mgmt.storage import StorageManagementClient from azure.core import exceptions from azure.core.pipeline.policies import RetryPolicy # 禁用自动重试 retry_policy = RetryPolicy(max_retries=0) storage_client = StorageManagementClient( credential="tokenCredential", subscription_id="subscriptionId", retry_policy=retry_policy ) while True: try: account_properties = storage_client.storage_accounts.get_properties( account_name="myStorageAccount", resource_group_name="myResourceGroup" ) print(account_properties) except exceptions.HttpResponseError as httpErr: if httpErr.status_code == 429: print("###捕获到429限流异常###") print(f"错误信息: {httpErr.message}") else: print(f"###捕获到其他HTTP异常###") print(httpErr.message) break
补充说明
- 你使用的
azure-core:1.26.4版本中,默认RetryPolicy会自动处理429、500、502、503、504这类可重试状态码,默认重试次数为3次。 - 自定义重试策略时,还可通过
retry_backoff_factor调整重试间隔的增长系数,或通过status_codes指定需要重试的状态码列表。
内容的提问来源于stack exchange,提问作者Nessy
相关产品推荐
相关产品推荐

