from fastapi import HTTPException, status class MarketplaceException(Exception): """Base exception for all marketplace errors.""" def __init__(self, message: str, code: str = "MARKETPLACE_ERROR"): self.message = message self.code = code super().__init__(message) class NotFoundError(MarketplaceException): """Raised when a requested resource does not exist.""" def __init__(self, resource: str, identifier: str = ""): detail = f"{resource} not found" if identifier: detail = f"{resource} '{identifier}' not found" super().__init__(detail, "NOT_FOUND") class UnauthorizedError(MarketplaceException): """Raised when an action is not permitted for the current user.""" def __init__(self, message: str = "Unauthorized"): super().__init__(message, "UNAUTHORIZED") class ValidationError(MarketplaceException): """Raised when input validation fails at the service layer.""" def __init__(self, message: str, details: dict = {}): self.details = details super().__init__(message, "VALIDATION_ERROR") class ConflictError(MarketplaceException): """Raised when a resource already exists (e.g. duplicate email).""" def __init__(self, message: str): super().__init__(message, "CONFLICT") class PaymentError(MarketplaceException): """Raised when a payment operation fails.""" def __init__(self, message: str): super().__init__(message, "PAYMENT_ERROR") def to_http_exception(exc: MarketplaceException) -> HTTPException: """Convert a MarketplaceException to a FastAPI HTTPException.""" status_map = { "NOT_FOUND": status.HTTP_404_NOT_FOUND, "UNAUTHORIZED": status.HTTP_403_FORBIDDEN, "VALIDATION_ERROR": status.HTTP_422_UNPROCESSABLE_ENTITY, "CONFLICT": status.HTTP_409_CONFLICT, "PAYMENT_ERROR": status.HTTP_402_PAYMENT_REQUIRED, } status_code = status_map.get(exc.code, status.HTTP_500_INTERNAL_SERVER_ERROR) return HTTPException( status_code=status_code, detail={"code": exc.code, "message": exc.message}, )