错误处理

章节概览

章节说明示例文件
异常层级异常类继承关系error_handling.py
StatusExceptionHTTP 状态码异常error_handling.py
RetryExhausted重试耗尽异常error_handling.py
统一捕获RequestException 基类error_handling.py

异常层级

hs-net 的所有异常都继承自 RequestException

RequestException            # 基类
├── StatusException          # HTTP 状态码非 2xx
├── TimeoutException         # 请求超时
├── ConnectionException      # 连接失败(DNS、SSL 等)
└── RetryExhausted           # 重试耗尽

StatusException

raise_status=True(默认)且响应状态码非 2xx 时抛出:

status.py
from hs_net import SyncNet, StatusException

with SyncNet() as net:
    try:
        resp = net.get("https://httpbin.org/status/404")
    except StatusException as e:
        print(f"状态码: {e.code}")   # 404
        print(f"URL: {e.url}")      # https://httpbin.org/status/404

关闭自动异常

no_raise.py
# 全局关闭
with SyncNet(raise_status=False) as net:
    resp = net.get("https://httpbin.org/status/404")
    if not resp.ok:
        print(f"请求失败: {resp.status_code}")

# 单次请求关闭
with SyncNet() as net:
    resp = net.get("https://httpbin.org/status/404", raise_status=False)

RetryExhausted

当所有重试都失败后抛出:

retry_exhausted.py
from hs_net import SyncNet, RetryExhausted

with SyncNet(retries=3) as net:
    try:
        resp = net.get("https://httpbin.org/status/500")
    except RetryExhausted as e:
        print(f"尝试次数: {e.attempts}")              # 3
        print(f"最后异常: {e.last_exception}")         # StatusException
        print(f"URL: {e.url}")                         # https://httpbin.org/status/500

TimeoutException & ConnectionException

timeout_connection.py
from hs_net import SyncNet, TimeoutException, ConnectionException

with SyncNet(verify=False, retries=0) as net:
    try:
        net.get("https://httpbin.org/delay/10", timeout=0.5)
    except TimeoutException as e:
        print(f"超时: timeout={e.timeout}s")

    try:
        net.get("https://this-domain-does-not-exist-12345.com")
    except ConnectionException as e:
        print(f"连接失败: {e.url}")

统一捕获

使用基类 RequestException 捕获所有 hs-net 异常:

catch_all.py
from hs_net import SyncNet, RequestException

with SyncNet() as net:
    try:
        resp = net.get("https://example.com")
    except RequestException as e:
        print(f"请求异常: {e}")