Files
mtusi2026lab7/app/errors.py
dawudukandCursor fb566d874c Перевести пароли на Argon2id и читать секреты через AppRole.
Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:40:28 +03:00

59 lines
1.6 KiB
Python

from typing import Dict, Optional
from starlette.responses import JSONResponse
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class AppError(Exception):
def __init__(
self,
status: int,
message: str,
www_authenticate: str | None = None,
headers: Optional[Dict[str, str]] = None,
) -> None:
super().__init__(message)
self.status = status
self.message = message
self.www_authenticate = www_authenticate
self.headers = headers or {}
def error_response(
status: int,
message: str,
request_id: str,
extra_headers: Optional[Dict[str, str]] = None,
) -> JSONResponse:
code = ERROR_CODES.get(status, "internal_error")
headers = {"X-Request-Id": request_id, "Content-Type": "application/json"}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(
status_code=status,
headers=headers,
content={"error": {"code": code, "message": message, "request_id": request_id}},
)
def from_app_error(exc: AppError, request_id: str) -> JSONResponse:
extra: Dict[str, str] = dict(exc.headers)
if exc.www_authenticate:
extra["WWW-Authenticate"] = exc.www_authenticate
return error_response(exc.status, exc.message, request_id, extra or None)