Files
mtusi2026lab5/app/errors/exceptions.py
T
2026-11-07 16:10:32 +03:00

110 lines
4.4 KiB
Python

from collections.abc import Mapping
from PIL import Image, UnidentifiedImageError
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class ApiError(Exception):
def __init__(
self,
status_code: int,
code: str,
message: str,
headers: Mapping[str, str] | None = None,
) -> None:
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers
def invalid_request(message: str = "Неверный запрос") -> ApiError:
"""Создаёт ошибку некорректного или недопустимого запроса."""
return ApiError(400, "invalid_request", message)
def unauthorized(
message: str = "Нет действительной аутентификации",
www_authenticate: str | None = None,
) -> ApiError:
"""Создаёт ошибку отсутствующей или недействительной аутентификации."""
headers = {"WWW-Authenticate": www_authenticate} if www_authenticate else None
return ApiError(401, "unauthorized", message, headers)
def unauthorized_basic(message: str = "Неверные учётные данные") -> ApiError:
"""401 для POST /auth/sessions (одинаковый для неверного username и пароля)."""
return unauthorized(message, BASIC_CHALLENGE)
def unauthorized_bearer(message: str = "Нет действительной сессии") -> ApiError:
"""401 для бизнес-endpoint: нет, истёк, отозван или неизвестен токен."""
return unauthorized(message, BEARER_CHALLENGE)
def not_found(message: str = "Объект не найден") -> ApiError:
"""Создаёт ошибку, указывающую на отсутствие запрошенного ресурса."""
return ApiError(404, "not_found", message)
def conflict(message: str = "Конфликт") -> ApiError:
"""Создаёт ошибку конфликта с текущим состоянием ресурса."""
return ApiError(409, "conflict", message)
def payload_too_large(message: str = "Слишком большое тело запроса") -> ApiError:
"""Создаёт ошибку, указывающую на превышение допустимого размера запроса."""
return ApiError(413, "payload_too_large", message)
def unsupported_media_type(
message: str = "Требуется Content-Type: application/json",
) -> ApiError:
"""Создаёт ошибку неподдерживаемого формата или типа содержимого запроса."""
return ApiError(415, "unsupported_media_type", message)
def rate_limited(retry_after: int = 1) -> ApiError:
"""Создаёт ошибку превышения допустимой частоты запросов."""
return ApiError(
429,
"rate_limited",
"Слишком много запросов",
{"Retry-After": str(max(1, retry_after))},
)
def unavailable(message: str = "Сервис временно недоступен") -> ApiError:
"""Создаёт ошибку временной недоступности сервиса."""
return ApiError(503, "unavailable", message)
def internal_error() -> ApiError:
"""Создаёт ошибку внутренней ошибки сервера."""
return ApiError(500, "internal_error", "Внутренняя ошибка сервера")
IMAGE_WORKER_ERRORS = (
ApiError, Image.DecompressionBombError, Image.DecompressionBombWarning,
MemoryError, UnidentifiedImageError, OSError, ValueError, SyntaxError,
)
def image_worker_error_code(error: Exception) -> int:
code = 2
resource_error = isinstance(error, (Image.DecompressionBombError, Image.DecompressionBombWarning, MemoryError))
declared_limit = isinstance(error, ApiError) and error.status_code == 413
if resource_error or declared_limit:
code = 3
return code
def image_validation_error(code: int) -> ApiError:
error = unsupported_media_type("Повреждённое изображение или несовпадение MIME")
if code == 3 or code < 0:
error = payload_too_large("Превышен лимит пикселей или ресурсов изображения")
return error