# api/errors.py import logging from fastapi import Request from fastapi.responses import JSONResponse from requests.exceptions import ConnectionError, HTTPError, Timeout from core.exceptions import BaseAppException from services.query_service import RateLimitExceeded logger = logging.getLogger(__name__) def add_exception_handlers(app): @app.exception_handler(RateLimitExceeded) async def rate_limit_handler(request: Request, exc: RateLimitExceeded): logger.warning(f"Rate limit exceeded on {request.url.path}") return JSONResponse( status_code=429, content={"status": "error", "detail": str(exc)}, ) @app.exception_handler(BaseAppException) async def app_exception_handler(request: Request, exc: BaseAppException): if exc.status_code >= 500: logger.error(f"App Error on {request.url.path}: {exc.message}", exc_info=True) else: logger.warning(f"App Warning on {request.url.path}: {exc.message}") return JSONResponse( status_code=exc.status_code, content={"status": "error", "detail": exc.message}, ) @app.exception_handler(Timeout) async def timeout_handler(request: Request, exc: Timeout): logger.error(f"Shopify timeout on {request.url.path}") return JSONResponse( status_code=504, content={"status": "error", "detail": "External service timed out"}, ) @app.exception_handler(ConnectionError) async def connection_handler(request: Request, exc: ConnectionError): logger.error(f"Connection error on {request.url.path}") return JSONResponse( status_code=502, content={"status": "error", "detail": "Could not connect to external service"}, ) @app.exception_handler(HTTPError) async def http_error_handler(request: Request, exc: HTTPError): logger.error(f"HTTP error on {request.url.path}: {exc}") return JSONResponse( status_code=400, content={"status": "error", "detail": f"External service error: {str(exc)}"}, ) @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): logger.warning(f"Value error on {request.url.path}: {exc}") return JSONResponse( status_code=400, content={"status": "error", "detail": str(exc)}, ) @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): logger.error(f"Unhandled exception on {request.url.path}: {exc}", exc_info=True) return JSONResponse( status_code=500, content={"status": "error", "detail": "Internal server error"}, )