from fastapi import FastAPI, Request, status from fastapi.responses import JSONResponse class AppError(Exception): """Base error class for the application""" def __init__(self, message: str, status_code: int): self.message = message self.status_code = status_code super().__init__(self.message) class NotFoundError(AppError): """Resource not found error""" def __init__(self, message: str): super().__init__(message, status_code=status.HTTP_404_NOT_FOUND) class ValidationError(AppError): """Data validation error""" def __init__(self, message: str): super().__init__(message, status_code=status.HTTP_400_BAD_REQUEST) class DatabaseError(AppError): """Database-related error""" def __init__(self, message: str): super().__init__(message, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) def add_error_handlers(app: FastAPI) -> None: """Configure exception handlers for the app""" @app.exception_handler(AppError) async def app_error_handler(request: Request, exc: AppError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={"detail": exc.message} ) @app.exception_handler(status.HTTP_404_NOT_FOUND) async def not_found_handler(request: Request, exc: Exception) -> JSONResponse: return JSONResponse( status_code=status.HTTP_404_NOT_FOUND, content={"detail": "Resource not found"} ) @app.exception_handler(status.HTTP_500_INTERNAL_SERVER_ERROR) async def server_error_handler(request: Request, exc: Exception) -> JSONResponse: return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "Internal server error"} )