Spaces:
Running
Running
| """ | |
| Exception handlers for Medical RAG AI Advisor API | |
| """ | |
| import logging | |
| from datetime import datetime | |
| from fastapi import Request, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from fastapi.exceptions import RequestValidationError | |
| from starlette.exceptions import HTTPException as StarletteHTTPException | |
| from api.models import ErrorResponse | |
| logger = logging.getLogger(__name__) | |
| async def http_exception_handler(request: Request, exc: HTTPException): | |
| """Handle HTTP exceptions""" | |
| logger.error(f"HTTP Exception: {exc.status_code} - {exc.detail}") | |
| return JSONResponse( | |
| status_code=exc.status_code, | |
| content=ErrorResponse( | |
| error="HTTP_ERROR", | |
| message=exc.detail, | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |
| async def validation_exception_handler(request: Request, exc: RequestValidationError): | |
| """Handle request validation errors""" | |
| errors = exc.errors() | |
| # Convert errors to JSON-serializable format | |
| serializable_errors = [] | |
| for error in errors: | |
| error_dict = { | |
| "type": error.get("type"), | |
| "loc": list(error.get("loc", [])), | |
| "msg": error.get("msg"), | |
| "input": str(error.get("input")) # Convert to string to ensure serializability | |
| } | |
| if "ctx" in error: | |
| error_dict["ctx"] = {k: str(v) for k, v in error["ctx"].items()} | |
| serializable_errors.append(error_dict) | |
| logger.error(f"Validation Error: {serializable_errors}") | |
| return JSONResponse( | |
| status_code=422, | |
| content=ErrorResponse( | |
| error="VALIDATION_ERROR", | |
| message="Request validation failed", | |
| details={"validation_errors": serializable_errors}, | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |
| async def general_exception_handler(request: Request, exc: Exception): | |
| """Handle general exceptions""" | |
| logger.error(f"Unhandled Exception: {type(exc).__name__} - {str(exc)}") | |
| return JSONResponse( | |
| status_code=500, | |
| content=ErrorResponse( | |
| error="INTERNAL_SERVER_ERROR", | |
| message="An internal server error occurred", | |
| details={"exception_type": type(exc).__name__}, | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |
| async def starlette_exception_handler(request: Request, exc: StarletteHTTPException): | |
| """Handle Starlette HTTP exceptions""" | |
| logger.error(f"Starlette HTTP Exception: {exc.status_code} - {exc.detail}") | |
| return JSONResponse( | |
| status_code=exc.status_code, | |
| content=ErrorResponse( | |
| error="HTTP_ERROR", | |
| message=exc.detail, | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |