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""" | |
| logger.error(f"Validation Error: {exc.errors()}") | |
| return JSONResponse( | |
| status_code=422, | |
| content=ErrorResponse( | |
| error="VALIDATION_ERROR", | |
| message="Request validation failed", | |
| details={"validation_errors": exc.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() | |
| ) | |