from fastapi import Request, status from fastapi.responses import JSONResponse from app.utils.errors import RagChatbotError from app.utils.logger import logger async def error_handler_middleware(request: Request, call_next): try: response = await call_next(request) return response except RagChatbotError as e: logger.error(f"RAG error: {str(e)}") return JSONResponse( status_code=e.status_code, content={"detail": str(e)} ) except Exception as e: logger.error(f"Unhandled error: {str(e)}") return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "Internal server error"} )