aibilly_backend_code/error.py
2026-03-10 16:44:04 +05:30

80 lines
2.4 KiB
Python

"""
Custom Error Classes
Framework-specific error handling for FastAPI
"""
from fastapi import HTTPException, status
from typing import Optional, Dict, Any
class AppError(Exception):
"""Base application error"""
def __init__(
self,
message: str,
status_code: int = 500,
details: Optional[Dict[str, Any]] = None
):
self.message = message
self.status_code = status_code
self.details = details or {}
super().__init__(self.message)
class ValidationError(AppError):
"""Validation error (400)"""
def __init__(self, message: str = "Validation error", errors: Optional[Dict] = None):
super().__init__(message, status_code=400, details={"errors": errors or {}})
class NotFoundError(AppError):
"""Resource not found error (404)"""
def __init__(self, resource: str = "Resource"):
super().__init__(f"{resource} not found", status_code=404)
class UnauthorizedError(AppError):
"""Unauthorized access error (401)"""
def __init__(self, message: str = "Unauthorized access"):
super().__init__(message, status_code=401)
class ForbiddenError(AppError):
"""Forbidden access error (403)"""
def __init__(self, message: str = "Forbidden access"):
super().__init__(message, status_code=403)
class ConflictError(AppError):
"""Resource conflict error (409)"""
def __init__(self, message: str = "Resource conflict"):
super().__init__(message, status_code=409)
class BadRequestError(AppError):
"""Bad request error (400)"""
def __init__(self, message: str = "Bad request"):
super().__init__(message, status_code=400)
# HTTP Exception helpers
def raise_validation_error(message: str, errors: Optional[Dict] = None):
"""Raise validation error as HTTPException"""
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={"message": message, "errors": errors or {}}
)
def raise_not_found_error(resource: str = "Resource"):
"""Raise not found error as HTTPException"""
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"message": f"{resource} not found"}
)
def raise_unauthorized_error(message: str = "Unauthorized access"):
"""Raise unauthorized error as HTTPException"""
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"message": message}
)