Files
sdb2-backend/app/utils/exceptions.py

121 lines
2.9 KiB
Python

"""Utility functions for common HTTP exception patterns."""
from fastapi import HTTPException, status
def raise_not_found(resource: str, identifier: str = None) -> None:
"""Raise a standardized 404 Not Found exception.
Args:
resource: Name of the resource that wasn't found
identifier: Optional identifier for the specific resource
Raises:
HTTPException with 404 status code
"""
if identifier:
detail = f"{resource} with ID {identifier} not found"
else:
detail = f"{resource} not found"
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=detail,
)
def raise_unauthorized(detail: str = "Could not validate credentials") -> None:
"""Raise a standardized 401 Unauthorized exception.
Args:
detail: Error message detail
Raises:
HTTPException with 401 status code
"""
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
)
def raise_bad_request(detail: str) -> None:
"""Raise a standardized 400 Bad Request exception.
Args:
detail: Error message detail
Raises:
HTTPException with 400 status code
"""
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=detail,
)
def raise_internal_server_error(detail: str, cause: Exception = None) -> None:
"""Raise a standardized 500 Internal Server Error exception.
Args:
detail: Error message detail
cause: Optional underlying exception
Raises:
HTTPException with 500 status code
"""
if cause:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=detail,
) from cause
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=detail,
)
def raise_payment_required(detail: str = "Insufficient credits") -> None:
"""Raise a standardized 402 Payment Required exception.
Args:
detail: Error message detail
Raises:
HTTPException with 402 status code
"""
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail=detail,
)
def raise_forbidden(detail: str = "Access forbidden") -> None:
"""Raise a standardized 403 Forbidden exception.
Args:
detail: Error message detail
Raises:
HTTPException with 403 status code
"""
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=detail,
)
def raise_conflict(detail: str) -> None:
"""Raise a standardized 409 Conflict exception.
Args:
detail: Error message detail
Raises:
HTTPException with 409 status code
"""
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=detail,
)