from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import ValidationError from sqlalchemy.exc import SQLAlchemyError from app.core.exceptions import TaskManagerException from app.schemas.responses import ErrorResponse def add_error_handlers(app: FastAPI) -> None: """Add error handlers to the FastAPI application. Args: app: FastAPI application """ @app.exception_handler(TaskManagerException) async def task_manager_exception_handler( request: Request, exc: TaskManagerException ) -> JSONResponse: """Handle TaskManagerException. Args: request: FastAPI request exc: TaskManagerException Returns: JSONResponse with error details """ return JSONResponse( status_code=exc.status_code, content=ErrorResponse(detail=exc.detail).model_dump(), ) @app.exception_handler(RequestValidationError) async def validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: """Handle RequestValidationError. Args: request: FastAPI request exc: RequestValidationError Returns: JSONResponse with error details """ return JSONResponse( status_code=422, content=ErrorResponse(detail=str(exc)).model_dump(), ) @app.exception_handler(ValidationError) async def pydantic_validation_exception_handler( request: Request, exc: ValidationError ) -> JSONResponse: """Handle Pydantic ValidationError. Args: request: FastAPI request exc: ValidationError Returns: JSONResponse with error details """ return JSONResponse( status_code=422, content=ErrorResponse(detail=str(exc)).model_dump(), ) @app.exception_handler(SQLAlchemyError) async def sqlalchemy_exception_handler( request: Request, exc: SQLAlchemyError ) -> JSONResponse: """Handle SQLAlchemy errors. Args: request: FastAPI request exc: SQLAlchemyError Returns: JSONResponse with error details """ return JSONResponse( status_code=500, content=ErrorResponse( detail="Database error occurred. Please try again later." ).model_dump(), ) @app.exception_handler(Exception) async def general_exception_handler( request: Request, exc: Exception ) -> JSONResponse: """Handle general exceptions. Args: request: FastAPI request exc: Exception Returns: JSONResponse with error details """ return JSONResponse( status_code=500, content=ErrorResponse( detail="An unexpected error occurred. Please try again later." ).model_dump(), )