如何实现健壮的错误处理和重试机制?
中等
答题要点
import asyncio
from functools import wraps
from typing import Type, Tuple
import random
# 简单重试装饰器
def retry(max_attempts: int = 3, delay: float = 1.0,
exceptions: Tuple[Type[Exception], ...] = (Exception,)):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_exception = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
if attempt < max_attempts - 1:
time.sleep(delay * (2 ** attempt)) # 指数退避
raise last_exception
return wrapper
return decorator
# 异步重试
def async_retry(max_attempts: int = 3, delay: float = 1.0,
backoff: float = 2.0, jitter: bool = True):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
last_exception = None
current_delay = delay
for attempt in range(max_attempts):
try:
return await func(*args, **kwargs)
except Exception as e:
last_exception = e
if attempt < max_attempts - 1:
wait_time = current_delay
if jitter:
wait_time *= (0.5 + random.random())
await asyncio.sleep(wait_time)
current_delay *= backoff
raise last_exception
return wrapper
return decorator
# tenacity库(更完整)
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=1, max=10),
retry=retry_if_exception_type((ConnectionError, TimeoutError))
)
async def fetch_with_retry(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
# 带回调的重试
class RetryWithCallback:
def __init__(self, max_attempts=3, on_retry=None, on_failure=None):
self.max_attempts = max_attempts
self.on_retry = on_retry
self.on_failure = on_failure
def __call__(self, func):
@wraps(func)
async def wrapper(*args, **kwargs):
for attempt in range(self.max_attempts):
try:
return await func(*args, **kwargs)
except Exception as e:
if attempt < self.max_attempts - 1:
if self.on_retry:
await self.on_retry(attempt, e)
await asyncio.sleep(2 ** attempt)
else:
if self.on_failure:
await self.on_failure(e)
raise
return wrapper
# 使用
@RetryWithCallback(
max_attempts=3,
on_retry=lambda a, e: print(f"Retry {a}: {e}"),
on_failure=lambda e: alert(f"Failed: {e}")
)
async def critical_operation():
pass
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题