errors.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. 自定义错误类
  3. 定义MCP Server使用的所有自定义异常类型。
  4. """
  5. from typing import Optional
  6. class MCPError(Exception):
  7. """MCP工具错误基类"""
  8. def __init__(self, message: str, code: str = "MCP_ERROR", suggestion: Optional[str] = None):
  9. super().__init__(message)
  10. self.code = code
  11. self.message = message
  12. self.suggestion = suggestion
  13. def to_dict(self) -> dict:
  14. """转换为字典格式"""
  15. error_dict = {
  16. "code": self.code,
  17. "message": self.message
  18. }
  19. if self.suggestion:
  20. error_dict["suggestion"] = self.suggestion
  21. return error_dict
  22. class DataNotFoundError(MCPError):
  23. """数据不存在错误"""
  24. def __init__(self, message: str, suggestion: Optional[str] = None):
  25. super().__init__(
  26. message=message,
  27. code="DATA_NOT_FOUND",
  28. suggestion=suggestion or "请检查日期范围或等待爬取任务完成"
  29. )
  30. class InvalidParameterError(MCPError):
  31. """参数无效错误"""
  32. def __init__(self, message: str, suggestion: Optional[str] = None):
  33. super().__init__(
  34. message=message,
  35. code="INVALID_PARAMETER",
  36. suggestion=suggestion or "请检查参数格式是否正确"
  37. )
  38. class ConfigurationError(MCPError):
  39. """配置错误"""
  40. def __init__(self, message: str, suggestion: Optional[str] = None):
  41. super().__init__(
  42. message=message,
  43. code="CONFIGURATION_ERROR",
  44. suggestion=suggestion or "请检查配置文件是否正确"
  45. )
  46. class PlatformNotSupportedError(MCPError):
  47. """平台不支持错误"""
  48. def __init__(self, platform: str):
  49. super().__init__(
  50. message=f"平台 '{platform}' 不受支持",
  51. code="PLATFORM_NOT_SUPPORTED",
  52. suggestion="支持的平台: zhihu, weibo, douyin, bilibili, baidu, toutiao, qq, 36kr, sspai, hellogithub, thepaper"
  53. )
  54. class CrawlTaskError(MCPError):
  55. """爬取任务错误"""
  56. def __init__(self, message: str, suggestion: Optional[str] = None):
  57. super().__init__(
  58. message=message,
  59. code="CRAWL_TASK_ERROR",
  60. suggestion=suggestion or "请稍后重试或查看日志"
  61. )
  62. class FileParseError(MCPError):
  63. """文件解析错误"""
  64. def __init__(self, file_path: str, reason: str):
  65. super().__init__(
  66. message=f"解析文件 {file_path} 失败: {reason}",
  67. code="FILE_PARSE_ERROR",
  68. suggestion="请检查文件格式是否正确"
  69. )