Spaces:
Sleeping
Sleeping
File size: 2,207 Bytes
e656014 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 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},
)
|