from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class TradeMateException(Exception): def __init__(self, code: int, message: str, detail: str = None): self.code = code self.message = message self.detail = detail class NotFoundError(TradeMateException): def __init__(self, resource: str = "Resource"): super().__init__(404, f"{resource} not found") class UnauthorizedError(TradeMateException): def __init__(self, detail: str = "Authentication required"): super().__init__(401, "Unauthorized", detail) class ForbiddenError(TradeMateException): def __init__(self, detail: str = "Insufficient permissions"): super().__init__(403, "Forbidden", detail) class QuotaExceededError(TradeMateException): def __init__(self, feature: str): super().__init__(429, "Quota exceeded", f"Daily limit reached for {feature}. Upgrade to Pro for more.") class TierRestrictionError(TradeMateException): def __init__(self, feature: str, required_tier: str): super().__init__( 402, "Upgrade required", f"{feature} requires {required_tier} plan", ) def register_exception_handlers(app: FastAPI): @app.exception_handler(TradeMateException) async def handle_tradmate_exception(request: Request, exc: TradeMateException): return JSONResponse( status_code=exc.code, content={ "error": exc.message, "detail": exc.detail, "code": exc.code, }, ) @app.exception_handler(Exception) async def handle_generic_exception(request: Request, exc: Exception): return JSONResponse( status_code=500, content={"error": "Internal server error", "detail": str(exc) if app.debug else "An unexpected error occurred"}, )