"""Custom exceptions and error handlers.""" from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from app.core.logging import get_logger logger = get_logger(__name__) class PlatformException(Exception): """Base exception for the platform.""" def __init__(self, message: str, status_code: int = 400): super().__init__(message) self.message = message self.status_code = status_code class AuthenticationError(PlatformException): """Authentication failed.""" def __init__(self, message: str = "Authentication failed"): super().__init__(message, status_code=401) class AuthorizationError(PlatformException): """Authorization failed.""" def __init__(self, message: str = "Forbidden"): super().__init__(message, status_code=403) class NotFoundError(PlatformException): """Resource not found.""" def __init__(self, message: str = "Resource not found"): super().__init__(message, status_code=404) class ConflictError(PlatformException): """Resource conflict.""" def __init__(self, message: str = "Conflict"): super().__init__(message, status_code=409) def add_exception_handlers(app: FastAPI) -> None: """Register global exception handlers.""" @app.exception_handler(PlatformException) async def platform_exception_handler(request: Request, exc: PlatformException): logger.warning("Platform exception: %s", exc.message) return JSONResponse( status_code=exc.status_code, content={"detail": exc.message}, ) @app.exception_handler(Exception) async def generic_exception_handler(request: Request, exc: Exception): logger.exception("Unhandled exception: %s", exc) return JSONResponse( status_code=500, content={"detail": "Internal server error"}, )