|
| 1 | +""" |
| 2 | +Standardized exception handling for pyplots API. |
| 3 | +
|
| 4 | +Provides consistent error responses and HTTP status codes. |
| 5 | +""" |
| 6 | + |
| 7 | +from fastapi import HTTPException, Request |
| 8 | +from fastapi.responses import JSONResponse |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | + |
| 12 | +# ===== Error Response Schemas ===== |
| 13 | + |
| 14 | + |
| 15 | +class ErrorDetail(BaseModel): |
| 16 | + """Standard error detail format.""" |
| 17 | + |
| 18 | + error: str |
| 19 | + detail: str |
| 20 | + path: str | None = None |
| 21 | + |
| 22 | + |
| 23 | +class ErrorResponse(BaseModel): |
| 24 | + """Standard error response format.""" |
| 25 | + |
| 26 | + status: int |
| 27 | + message: str |
| 28 | + errors: list[ErrorDetail] | None = None |
| 29 | + |
| 30 | + |
| 31 | +# ===== Custom Exceptions ===== |
| 32 | + |
| 33 | + |
| 34 | +class PyplotsException(Exception): |
| 35 | + """Base exception for pyplots API.""" |
| 36 | + |
| 37 | + def __init__(self, message: str, status_code: int = 500): |
| 38 | + self.message = message |
| 39 | + self.status_code = status_code |
| 40 | + super().__init__(message) |
| 41 | + |
| 42 | + |
| 43 | +class ResourceNotFoundError(PyplotsException): |
| 44 | + """Resource not found (404).""" |
| 45 | + |
| 46 | + def __init__(self, resource: str, identifier: str): |
| 47 | + message = f"{resource} '{identifier}' not found" |
| 48 | + super().__init__(message, status_code=404) |
| 49 | + self.resource = resource |
| 50 | + self.identifier = identifier |
| 51 | + |
| 52 | + |
| 53 | +class DatabaseNotConfiguredError(PyplotsException): |
| 54 | + """Database not configured (503).""" |
| 55 | + |
| 56 | + def __init__(self): |
| 57 | + message = "Database not configured. Please set DATABASE_URL or INSTANCE_CONNECTION_NAME environment variable." |
| 58 | + super().__init__(message, status_code=503) |
| 59 | + |
| 60 | + |
| 61 | +class ExternalServiceError(PyplotsException): |
| 62 | + """External service failure (502).""" |
| 63 | + |
| 64 | + def __init__(self, service: str, detail: str): |
| 65 | + message = f"External service '{service}' error: {detail}" |
| 66 | + super().__init__(message, status_code=502) |
| 67 | + self.service = service |
| 68 | + |
| 69 | + |
| 70 | +class ValidationError(PyplotsException): |
| 71 | + """Validation error (400).""" |
| 72 | + |
| 73 | + def __init__(self, detail: str): |
| 74 | + super().__init__(f"Validation failed: {detail}", status_code=400) |
| 75 | + |
| 76 | + |
| 77 | +# ===== Exception Handlers ===== |
| 78 | + |
| 79 | + |
| 80 | +async def pyplots_exception_handler(request: Request, exc: PyplotsException) -> JSONResponse: |
| 81 | + """Handle PyplotsException and return standardized JSON response.""" |
| 82 | + return JSONResponse( |
| 83 | + status_code=exc.status_code, |
| 84 | + content={"status": exc.status_code, "message": exc.message, "path": request.url.path}, |
| 85 | + ) |
| 86 | + |
| 87 | + |
| 88 | +async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse: |
| 89 | + """Handle FastAPI HTTPException with standardized format.""" |
| 90 | + return JSONResponse( |
| 91 | + status_code=exc.status_code, |
| 92 | + content={"status": exc.status_code, "message": exc.detail, "path": request.url.path}, |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +async def generic_exception_handler(request: Request, exc: Exception) -> JSONResponse: |
| 97 | + """Handle unexpected exceptions with 500 status.""" |
| 98 | + return JSONResponse( |
| 99 | + status_code=500, |
| 100 | + content={ |
| 101 | + "status": 500, |
| 102 | + "message": "Internal server error", |
| 103 | + "detail": str(exc) if isinstance(exc, Exception) else "An unexpected error occurred", |
| 104 | + "path": request.url.path, |
| 105 | + }, |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +# ===== Helper Functions ===== |
| 110 | + |
| 111 | + |
| 112 | +def raise_not_found(resource: str, identifier: str) -> None: |
| 113 | + """ |
| 114 | + Raise a standardized 404 error. |
| 115 | +
|
| 116 | + Args: |
| 117 | + resource: Resource type (e.g., "Spec", "Library") |
| 118 | + identifier: Resource identifier |
| 119 | +
|
| 120 | + Raises: |
| 121 | + ResourceNotFoundError: Always raises |
| 122 | + """ |
| 123 | + raise ResourceNotFoundError(resource, identifier) |
| 124 | + |
| 125 | + |
| 126 | +def raise_database_not_configured() -> None: |
| 127 | + """ |
| 128 | + Raise a standardized 503 error for unconfigured database. |
| 129 | +
|
| 130 | + Raises: |
| 131 | + DatabaseNotConfiguredError: Always raises |
| 132 | + """ |
| 133 | + raise DatabaseNotConfiguredError() |
| 134 | + |
| 135 | + |
| 136 | +def raise_external_service_error(service: str, detail: str) -> None: |
| 137 | + """ |
| 138 | + Raise a standardized 502 error for external service failures. |
| 139 | +
|
| 140 | + Args: |
| 141 | + service: Service name (e.g., "GCS", "GitHub API") |
| 142 | + detail: Error details |
| 143 | +
|
| 144 | + Raises: |
| 145 | + ExternalServiceError: Always raises |
| 146 | + """ |
| 147 | + raise ExternalServiceError(service, detail) |
| 148 | + |
| 149 | + |
| 150 | +def raise_validation_error(detail: str) -> None: |
| 151 | + """ |
| 152 | + Raise a standardized 400 error for validation failures. |
| 153 | +
|
| 154 | + Args: |
| 155 | + detail: Validation error details |
| 156 | +
|
| 157 | + Raises: |
| 158 | + ValidationError: Always raises |
| 159 | + """ |
| 160 | + raise ValidationError(detail) |
0 commit comments