from fastapi import FastAPI, Request, status from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError import logging logger = logging.getLogger("plain_api_errors") def setup_exception_handlers(app: FastAPI): @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): logger.error(f"Value Error: {exc}") return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"detail": str(exc)} ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): logger.error(f"Validation Error: {exc.errors()}") return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()} ) @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): logger.error(f"Unexpected Error: {exc}", exc_info=True) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "An internal server error occurred."} )