You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化含多except分支的try/except代码块?附API请求重试代码

简化多分支try/except+重试逻辑的几种思路

嘿,我来给你几个实用的简化方案,让这段代码更清爽、更易维护:

思路1:合并同类异常,统一处理公共逻辑

requests库的大部分异常(比如HTTPError、ConnectionError)都继承自RequestException父类,咱们可以先捕获这个大类,再区分具体异常类型处理个性化提示,把重复的计数、邮件通知逻辑抽出来统一处理:

import requests
from requests.exceptions import RequestException, HTTPError

max_attempts = 10
attempts = 0
response = None

while attempts < max_attempts:
    try:
        response = requests.post(
            server, 
            data=contents, 
            auth=requests.auth.HTTPBasicAuth(service_userid, service_pswd)
        )
        response.raise_for_status()
        break  # 请求成功,直接跳出循环
    except RequestException as err:
        # 根据异常类型打印对应提示
        if isinstance(err, HTTPError):
            print(f'Http Error: {err}')
        else:
            print(f'Error Connecting: {err}')
        
        attempts += 1
        # 最后一次尝试失败时发送告警邮件
        if attempts == max_attempts:
            error_type = type(err).__name__
            body = f'{error_type}: {str(err)}'
            subject = 'API Request Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)

# 后续可根据response是否为None判断请求是否成功
if not response:
    print("所有请求尝试均失败")

这样就避免了多个except分支重复写相同的计数和邮件逻辑,代码结构更紧凑。

思路2:封装重试逻辑为独立函数

如果这段API请求逻辑会在多处复用,把重试和异常处理封装成一个独立函数会更优雅,主代码只需要关注核心业务:

import requests
from requests.exceptions import RequestException, HTTPError

def send_api_request(server, contents, auth, max_attempts=10):
    for attempt in range(max_attempts):
        try:
            response = requests.post(server, data=contents, auth=auth)
            response.raise_for_status()
            return response  # 成功则返回响应对象
        except RequestException as err:
            # 打印对应错误信息
            msg = f'Http Error: {err}' if isinstance(err, HTTPError) else f'Error Connecting: {err}'
            print(msg)
            
            # 最后一次失败触发邮件告警
            if attempt == max_attempts - 1:
                body = f'{type(err).__name__}: {str(err)}'
                subject = 'API Request Failure'
                sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
    return None  # 所有尝试失败返回None

# 调用函数
auth = requests.auth.HTTPBasicAuth(service_userid, service_pswd)
response = send_api_request(server, contents, auth)

这种方式把重试逻辑和业务请求解耦,代码的可读性和复用性都大幅提升,后续修改重试次数或异常规则也只需要调整这一个函数。

额外小优化

  • 用f-string格式化字符串,比传统的+拼接更简洁直观;
  • 把max_attempts定义为常量,后续调整重试次数更方便;
  • 请求成功后直接break或return,避免不必要的循环执行。

内容的提问来源于stack exchange,提问作者max04

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:21:47