from fastapi import HTTPException, Request, status from fastapi.responses import JSONResponse class BaseAPIException(HTTPException): def __init__( self, status_code: int, detail: str = None, headers: dict = None, ): super().__init__(status_code=status_code, detail=detail, headers=headers) class ItemNotFoundException(BaseAPIException): def __init__(self, item_id: int): super().__init__( status_code=status.HTTP_404_NOT_FOUND, detail=f"Item with ID {item_id} not found", ) class ValidationError(BaseAPIException): def __init__(self, detail: str = "Validation error"): super().__init__( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=detail, ) async def validation_exception_handler(request: Request, exc: ValidationError): return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail}, ) async def item_not_found_handler(request: Request, exc: ItemNotFoundException): return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail}, )