File size: 4,808 Bytes
194469b | 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 | """Global exception classes and handlers."""
from datetime import datetime, timezone
from typing import Any
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
from models import ErrorResponse
class BaseAPIException(HTTPException):
"""Base exception class for API errors."""
def __init__(
self,
status_code: int,
message: str,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> None:
self.message = message
self.details = details
super().__init__(status_code=status_code, detail=message, headers=headers)
class ValidationError(BaseAPIException):
"""Validation error exception."""
def __init__(
self,
message: str = "Validation failed",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
message=message,
details=details,
)
class NotFoundError(BaseAPIException):
"""Resource not found exception."""
def __init__(
self,
message: str = "Resource not found",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_404_NOT_FOUND,
message=message,
details=details,
)
class ConflictError(BaseAPIException):
"""Resource conflict exception."""
def __init__(
self,
message: str = "Resource conflict",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_409_CONFLICT,
message=message,
details=details,
)
class UnauthorizedError(BaseAPIException):
"""Unauthorized access exception."""
def __init__(
self,
message: str = "Unauthorized access",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
message=message,
details=details,
headers={"WWW-Authenticate": "Bearer"},
)
class ForbiddenError(BaseAPIException):
"""Forbidden access exception."""
def __init__(
self,
message: str = "Forbidden access",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_403_FORBIDDEN,
message=message,
details=details,
)
class InternalServerError(BaseAPIException):
"""Internal server error exception."""
def __init__(
self,
message: str = "Internal server error",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
message=message,
details=details,
)
class BadRequestError(BaseAPIException):
"""Bad request exception."""
def __init__(
self,
message: str = "Bad request",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_400_BAD_REQUEST,
message=message,
details=details,
)
class ServiceUnavailableError(BaseAPIException):
"""Service unavailable exception."""
def __init__(
self,
message: str = "Service temporarily unavailable",
details: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
message=message,
details=details,
)
async def base_api_exception_handler(
request: Request, exc: BaseAPIException
) -> JSONResponse:
"""Handle BaseAPIException and return structured error response."""
error_response = ErrorResponse(
error=exc.__class__.__name__,
message=exc.message,
details=exc.details,
timestamp=datetime.now(timezone.utc),
path=str(request.url.path),
)
return JSONResponse(
status_code=exc.status_code,
content=error_response.model_dump(),
headers=exc.headers,
)
async def general_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""Handle general exceptions and return structured error response."""
error_response = ErrorResponse(
error="InternalServerError",
message="An unexpected error occurred",
details={"exception_type": exc.__class__.__name__},
timestamp=datetime.now(timezone.utc),
path=str(request.url.path),
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=error_response.model_dump(),
)
|