solution
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
"""Ошибки API и единый конверт ответа контракта."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Mapping
|
||||
|
||||
INVALID_REQUEST = "invalid_request"
|
||||
UNAUTHORIZED = "unauthorized"
|
||||
NOT_FOUND = "not_found"
|
||||
CONFLICT = "conflict"
|
||||
PAYLOAD_TOO_LARGE = "payload_too_large"
|
||||
UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"
|
||||
RATE_LIMITED = "rate_limited"
|
||||
UNAVAILABLE = "unavailable"
|
||||
INTERNAL_ERROR = "internal_error"
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
DEFAULT_CODE_BY_STATUS: Mapping[int, str] = {
|
||||
400: INVALID_REQUEST,
|
||||
401: UNAUTHORIZED,
|
||||
403: UNAUTHORIZED,
|
||||
404: NOT_FOUND,
|
||||
405: INVALID_REQUEST,
|
||||
409: CONFLICT,
|
||||
413: PAYLOAD_TOO_LARGE,
|
||||
415: UNSUPPORTED_MEDIA_TYPE,
|
||||
429: RATE_LIMITED,
|
||||
500: INTERNAL_ERROR,
|
||||
503: UNAVAILABLE,
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""Ошибка, которую можно безопасно показать клиенту в конверте контракта."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = dict(headers or {})
|
||||
|
||||
|
||||
def code_for_status(status: int) -> str:
|
||||
"""Подбирает код конверта для статуса, пришедшего извне контракта."""
|
||||
if status in DEFAULT_CODE_BY_STATUS:
|
||||
return DEFAULT_CODE_BY_STATUS[status]
|
||||
return INTERNAL_ERROR if status >= 500 else INVALID_REQUEST
|
||||
|
||||
|
||||
def invalid_request(message: str) -> ApiError:
|
||||
return ApiError(400, INVALID_REQUEST, message)
|
||||
|
||||
|
||||
def unauthorized(message: str, challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
"""401 с challenge схемы: Basic — только на создании сессии, иначе Bearer."""
|
||||
return ApiError(401, UNAUTHORIZED, message, headers={"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def not_found(message: str) -> ApiError:
|
||||
"""Чужой объект неотличим от отсутствующего: 403 не используется."""
|
||||
return ApiError(404, NOT_FOUND, message)
|
||||
|
||||
|
||||
def conflict(message: str) -> ApiError:
|
||||
return ApiError(409, CONFLICT, message)
|
||||
|
||||
|
||||
def unavailable(message: str) -> ApiError:
|
||||
"""503: зависимость недоступна, отказ ограничен и не раскрывает внутренностей."""
|
||||
return ApiError(503, UNAVAILABLE, message)
|
||||
Reference in New Issue
Block a user