业务背景
编写爬虫、连接远程数据库等操作常常因为网络问题失败,需要我们重新尝试。为了避免对整个程序的影响,我们可以使用装饰器让特定模块再出错时自动重新运行。
代码
import functools
def retry_on_error(max_attempts=2):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
print(f"函数 {func.__name__} 运行出错:{e}. 正在尝试第 {attempts} 次重新运行...")
else:
raise RuntimeError(f"函数 {func.__name__} 已达到最大尝试次数 {max_attempts},仍无法成功运行")
return wrapper
return decorator
# 使用装饰器来修饰函数
@retry_on_error(max_attempts=3)
def potentially_unstable_function():
import random
if random.random() < 0.5:
raise ValueError("随机错误")
els