Files
mtusi2026lab2/app/errors.py
T
RainakandClaude Opus 5.5 0c5846173b
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР2: PostgreSQL, сессии и Valkey (на 4)
API мессенджера на FastAPI + asyncpg, миграции, Argon2id, Bearer-сессии
в PostgreSQL с кэшем Valkey, compose-стенд, restart.sh, тесты уровня 4,
EXPLAIN и отчёт.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:49:32 +03:00

49 lines
1.8 KiB
Python

"""Единый формат ошибок {"error":{"code","message","request_id"}}."""
from contextvars import ContextVar
from fastapi.responses import JSONResponse
request_id_var: ContextVar[str] = ContextVar('request_id', default='-')
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
def invalid(message: str = 'Некорректный запрос') -> ApiError:
return ApiError(400, 'invalid_request', message)
def not_found() -> ApiError:
# Одинаковый ответ для "нет такого" и "чужое": существование чужого чата не раскрывается.
return ApiError(404, 'not_found', 'Объект не найден')
def unauthorized_bearer() -> ApiError:
return ApiError(401, 'unauthorized', 'Требуется действительная сессия', {'WWW-Authenticate': BEARER_CHALLENGE})
def unauthorized_basic() -> ApiError:
return ApiError(401, 'unauthorized', 'Неверные учётные данные', {'WWW-Authenticate': BASIC_CHALLENGE})
def unavailable() -> ApiError:
return ApiError(503, 'unavailable', 'Сервис временно недоступен')
def error_response(status: int, code: str, message: str, headers: dict | None = None) -> JSONResponse:
rid = request_id_var.get()
return JSONResponse(
status_code=status,
content={'error': {'code': code, 'message': message, 'request_id': rid}},
headers=headers,
)