error_handler.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import sys
  2. import traceback
  3. from typing import Callable, Any, Optional, Dict, List, Type, Union
  4. from functools import wraps
  5. import time
  6. class ProcessingError(Exception):
  7. """数据处理错误的基类"""
  8. def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
  9. self.message = message
  10. self.details = details or {}
  11. super().__init__(message)
  12. class DataValidationError(ProcessingError):
  13. """数据验证错误"""
  14. pass
  15. class ResourceNotFoundError(ProcessingError):
  16. """资源未找到错误"""
  17. pass
  18. class PluginError(ProcessingError):
  19. """插件相关错误"""
  20. pass
  21. class ConfigurationError(ProcessingError):
  22. """配置错误"""
  23. pass
  24. class EngineExecutionError(ProcessingError):
  25. """引擎执行错误"""
  26. pass
  27. class ErrorHandler:
  28. """错误处理器,提供统一的异常处理机制"""
  29. @staticmethod
  30. def handle_exceptions(func: Callable) -> Callable:
  31. """装饰器:用于处理函数执行期间的异常"""
  32. @wraps(func)
  33. def wrapper(*args, **kwargs):
  34. try:
  35. return func(*args, **kwargs)
  36. except Exception as e:
  37. ErrorHandler.handle_exception(e, {"function": func.__name__})
  38. raise
  39. return wrapper
  40. @staticmethod
  41. def handle_exception(exc: Exception, context: Optional[Dict[str, Any]] = None) -> None:
  42. """处理异常,记录日志并提供上下文信息"""
  43. context = context or {}
  44. # 获取异常的堆栈跟踪
  45. exc_type, exc_value, exc_traceback = sys.exc_info()
  46. stack_trace = traceback.format_exception(exc_type, exc_value, exc_traceback)
  47. # 打印异常信息
  48. error_message = f"异常: {type(exc).__name__}: {str(exc)}"
  49. print(error_message)
  50. # 打印上下文信息
  51. if context:
  52. print(f"上下文信息: {context}")
  53. # 打印堆栈跟踪
  54. print("堆栈跟踪:\n" + "".join(stack_trace))
  55. @staticmethod
  56. def retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0,
  57. exceptions: Union[Type[Exception], List[Type[Exception]]] = Exception):
  58. """重试装饰器,用于自动重试可能失败的操作
  59. Args:
  60. max_attempts: 最大尝试次数
  61. delay: 初始延迟时间(秒)
  62. backoff: 延迟时间的增长因子
  63. exceptions: 需要捕获的异常类型
  64. """
  65. def decorator(func):
  66. @wraps(func)
  67. def wrapper(*args, **kwargs):
  68. attempt = 1
  69. current_delay = delay
  70. while attempt <= max_attempts:
  71. try:
  72. return func(*args, **kwargs)
  73. except exceptions as e:
  74. if attempt == max_attempts:
  75. print(f"重试{max_attempts}次后失败: {func.__name__}")
  76. raise
  77. print(f"尝试 {attempt}/{max_attempts} 失败: {func.__name__}, 错误: {e}")
  78. print(f"将在 {current_delay:.2f} 秒后重试...")
  79. time.sleep(current_delay)
  80. attempt += 1
  81. current_delay *= backoff
  82. return wrapper
  83. return decorator
  84. @staticmethod
  85. def validate_input(validator: Callable[[Any], bool], error_message: str = "输入验证失败"):
  86. """输入验证装饰器,用于验证函数输入参数
  87. Args:
  88. validator: 验证函数,接收函数的所有参数并返回布尔值
  89. error_message: 验证失败时的错误消息
  90. """
  91. def decorator(func):
  92. @wraps(func)
  93. def wrapper(*args, **kwargs):
  94. if not validator(*args, **kwargs):
  95. raise DataValidationError(error_message)
  96. return func(*args, **kwargs)
  97. return wrapper
  98. return decorator
  99. @staticmethod
  100. def measure_performance(func):
  101. """性能测量装饰器,用于记录函数执行时间"""
  102. @wraps(func)
  103. def wrapper(*args, **kwargs):
  104. start_time = time.time()
  105. result = func(*args, **kwargs)
  106. end_time = time.time()
  107. execution_time = end_time - start_time
  108. print(f"函数 {func.__name__} 执行时间: {execution_time:.4f} 秒")
  109. return result
  110. return wrapper
  111. @staticmethod
  112. def safe_execute(fallback_value: Any = None, log_exception: bool = True):
  113. """安全执行装饰器,捕获异常并返回默认值
  114. Args:
  115. fallback_value: 发生异常时返回的默认值
  116. log_exception: 是否记录异常信息
  117. """
  118. def decorator(func):
  119. @wraps(func)
  120. def wrapper(*args, **kwargs):
  121. try:
  122. return func(*args, **kwargs)
  123. except Exception as e:
  124. if log_exception:
  125. print(f"函数 {func.__name__} 执行失败: {e}")
  126. return fallback_value
  127. return wrapper
  128. return decorator