"""Standardized error responses for the API. All endpoints return consistent error format: { "success": false, "error": "Human-readable message", "code": "MACHINE_READABLE_CODE", // optional "remaining_requests": 95, // optional (rate limit info) } This ensures both middleware errors and route errors have the same shape so the frontend always reads from `response.error`. """ from fastapi import HTTPException, status from typing import Any, Dict, Optional class AppError(Exception): """Custom application-level error with machine-readable code.""" def __init__( self, message: str, code: str = "UNKNOWN_ERROR", status_code: int = status.HTTP_400_BAD_REQUEST, ): self.message = message self.code = code self.status_code = status_code def error_response(message: str, code: Optional[str] = None, remaining: Optional[int] = None) -> Dict[str, Any]: """Build a standardized error dict.""" result = {"success": False, "error": message} if code: result["code"] = code if remaining is not None: result["remaining_requests"] = remaining return result def raise_error(message: str, code: str = "UNKNOWN_ERROR", status_code: int = 400): """Raise an HTTPException with standardized format.""" raise HTTPException( status_code=status_code, detail=error_response(message, code), ) # Common error codes class ErrorCode: INVALID_CREDENTIALS = "INVALID_CREDENTIALS" DUPLICATE_EMAIL = "DUPLICATE_EMAIL" TOKEN_EXPIRED = "TOKEN_EXPIRED" TOKEN_INVALID = "TOKEN_INVALID" RATE_LIMITED = "RATE_LIMITED" NOT_FOUND = "NOT_FOUND" NOT_AUTHORIZED = "NOT_AUTHORIZED" NETWORK_ERROR = "NETWORK_ERROR" VALIDATION_ERROR = "VALIDATION_ERROR" DB_ERROR = "DATABASE_ERROR"