Spaces:
Sleeping
Sleeping
File size: 9,548 Bytes
e98cc10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | """
Custom Exceptions Module
Defines structured exceptions for better error handling and API responses.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Optional
from enum import Enum
# =============================================================================
# ERROR CODES
# =============================================================================
class ErrorCode(str, Enum):
"""Standard error codes for API responses."""
# Validation errors (400)
INVALID_URL = "INVALID_URL"
INVALID_QUERY = "INVALID_QUERY"
INVALID_TAG = "INVALID_TAG"
INVALID_FORMAT = "INVALID_FORMAT"
VALIDATION_ERROR = "VALIDATION_ERROR"
# Authentication/Authorization (401/403)
UNAUTHORIZED = "UNAUTHORIZED"
FORBIDDEN = "FORBIDDEN"
API_KEY_MISSING = "API_KEY_MISSING"
API_KEY_INVALID = "API_KEY_INVALID"
# Not found (404)
ARTICLE_NOT_FOUND = "ARTICLE_NOT_FOUND"
RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND"
# Rate limiting (429)
RATE_LIMITED = "RATE_LIMITED"
QUOTA_EXCEEDED = "QUOTA_EXCEEDED"
# Server errors (500)
INTERNAL_ERROR = "INTERNAL_ERROR"
SCRAPE_FAILED = "SCRAPE_FAILED"
EXTRACTION_FAILED = "EXTRACTION_FAILED"
RENDER_FAILED = "RENDER_FAILED"
# External service errors (502/503)
MEDIUM_UNAVAILABLE = "MEDIUM_UNAVAILABLE"
SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
EXTERNAL_API_ERROR = "EXTERNAL_API_ERROR"
# Timeout (504)
TIMEOUT = "TIMEOUT"
# =============================================================================
# ERROR RESPONSE
# =============================================================================
@dataclass
class ErrorResponse:
"""Structured error response for API/UI."""
code: ErrorCode
message: str
details: Optional[dict[str, Any]] = None
http_status: int = 400
recoverable: bool = True
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
result = {
"error": {
"code": self.code.value,
"message": self.message,
}
}
if self.details:
result["error"]["details"] = self.details
return result
def to_user_message(self) -> str:
"""Get user-friendly error message."""
return self.message
# =============================================================================
# BASE EXCEPTION
# =============================================================================
class MediumMCPError(Exception):
"""
Base exception for all Medium-MCP errors.
All custom exceptions should inherit from this class.
"""
code: ErrorCode = ErrorCode.INTERNAL_ERROR
http_status: int = 500
recoverable: bool = True
def __init__(
self,
message: str,
details: Optional[dict[str, Any]] = None,
cause: Optional[Exception] = None,
) -> None:
super().__init__(message)
self.message = message
self.details = details or {}
self.cause = cause
def to_response(self) -> ErrorResponse:
"""Convert exception to ErrorResponse."""
return ErrorResponse(
code=self.code,
message=self.message,
details=self.details,
http_status=self.http_status,
recoverable=self.recoverable,
)
# =============================================================================
# VALIDATION EXCEPTIONS
# =============================================================================
class ValidationError(MediumMCPError):
"""Raised when input validation fails."""
code = ErrorCode.VALIDATION_ERROR
http_status = 400
class InvalidURLError(ValidationError):
"""Raised when URL is invalid."""
code = ErrorCode.INVALID_URL
def __init__(self, url: str, reason: str = "Invalid URL format") -> None:
super().__init__(
message=f"Invalid URL: {reason}",
details={"url": url[:100], "reason": reason},
)
class InvalidQueryError(ValidationError):
"""Raised when search query is invalid."""
code = ErrorCode.INVALID_QUERY
def __init__(self, query: str, reason: str = "Invalid query") -> None:
super().__init__(
message=f"Invalid search query: {reason}",
details={"query": query[:100], "reason": reason},
)
class InvalidTagError(ValidationError):
"""Raised when tag is invalid."""
code = ErrorCode.INVALID_TAG
def __init__(self, tag: str, reason: str = "Invalid tag format") -> None:
super().__init__(
message=f"Invalid tag: {reason}",
details={"tag": tag[:50], "reason": reason},
)
# =============================================================================
# SCRAPING EXCEPTIONS
# =============================================================================
class ScrapeError(MediumMCPError):
"""Base exception for scraping failures."""
code = ErrorCode.SCRAPE_FAILED
http_status = 502
class ArticleNotFoundError(ScrapeError):
"""Raised when article cannot be found."""
code = ErrorCode.ARTICLE_NOT_FOUND
http_status = 404
def __init__(self, url: str) -> None:
super().__init__(
message=f"Article not found: {url}",
details={"url": url},
)
class ExtractionError(ScrapeError):
"""Raised when content extraction fails."""
code = ErrorCode.EXTRACTION_FAILED
def __init__(self, url: str, tier: str = "unknown") -> None:
super().__init__(
message=f"Failed to extract content from {url}",
details={"url": url, "tier": tier},
)
class PaywallError(ScrapeError):
"""Raised when article is paywalled."""
code = ErrorCode.SCRAPE_FAILED
recoverable = False
def __init__(self, url: str) -> None:
super().__init__(
message="Article is behind a paywall",
details={"url": url, "paywalled": True},
)
# =============================================================================
# RATE LIMITING EXCEPTIONS
# =============================================================================
class RateLimitError(MediumMCPError):
"""Raised when rate limit is exceeded."""
code = ErrorCode.RATE_LIMITED
http_status = 429
def __init__(
self,
message: str = "Rate limit exceeded",
retry_after: Optional[int] = None,
) -> None:
details = {}
if retry_after:
details["retry_after_seconds"] = retry_after
super().__init__(message=message, details=details)
self.retry_after = retry_after
class QuotaExceededError(RateLimitError):
"""Raised when API quota is exceeded."""
code = ErrorCode.QUOTA_EXCEEDED
recoverable = False
def __init__(self, service: str = "Unknown") -> None:
super().__init__(
message=f"API quota exceeded for {service}",
)
# =============================================================================
# EXTERNAL SERVICE EXCEPTIONS
# =============================================================================
class ExternalServiceError(MediumMCPError):
"""Raised when an external service fails."""
code = ErrorCode.EXTERNAL_API_ERROR
http_status = 502
def __init__(
self,
service: str,
message: str = "External service error",
status_code: Optional[int] = None,
) -> None:
details = {"service": service}
if status_code:
details["status_code"] = status_code
super().__init__(message=f"{service}: {message}", details=details)
class MediumUnavailableError(ExternalServiceError):
"""Raised when Medium is unavailable."""
code = ErrorCode.MEDIUM_UNAVAILABLE
http_status = 503
def __init__(self, message: str = "Medium is currently unavailable") -> None:
super().__init__(service="Medium", message=message)
class TimeoutError(MediumMCPError):
"""Raised when an operation times out."""
code = ErrorCode.TIMEOUT
http_status = 504
def __init__(
self,
operation: str = "request",
timeout_seconds: Optional[int] = None,
) -> None:
details = {"operation": operation}
if timeout_seconds:
details["timeout_seconds"] = timeout_seconds
super().__init__(
message=f"Operation timed out: {operation}",
details=details,
)
# =============================================================================
# RENDER EXCEPTIONS
# =============================================================================
class RenderError(MediumMCPError):
"""Raised when rendering fails."""
code = ErrorCode.RENDER_FAILED
http_status = 500
def __init__(
self,
format: str = "unknown",
message: str = "Render failed",
) -> None:
super().__init__(
message=f"Failed to render {format}: {message}",
details={"format": format},
)
class PDFRenderError(RenderError):
"""Raised when PDF rendering fails."""
def __init__(self, message: str = "PDF generation failed") -> None:
super().__init__(format="PDF", message=message)
|