feat: функционал первой лабы перенос

This commit is contained in:
Enterxx2
2026-10-11 13:24:29 +03:00
parent 65003b6119
commit a6c74c9bb0
90 changed files with 2746 additions and 1 deletions
+3
View File
@@ -0,0 +1,3 @@
from .exceptions import register_exception_handlers
__all__ = ["register_exception_handlers"]
@@ -0,0 +1,57 @@
from http import HTTPStatus
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from application.api.utils import error_response, get_request_id
from domain.errors import AppError, ErrorCode, InvalidRequestError, NotFoundError
async def app_error_handler(request: Request, error: Exception) -> JSONResponse:
"""Доменные ошибки сервисов и репозиториев"""
assert isinstance(error, AppError)
return error_response(
get_request_id(request), error.status_code, error.code, error.message
)
async def validation_error_handler(request: Request, error: Exception) -> JSONResponse:
"""Malformed JSON, лишние поля, неверные типы, uuid и limit — 400"""
assert isinstance(error, RequestValidationError)
return error_response(
get_request_id(request),
InvalidRequestError.status_code,
InvalidRequestError.code,
_describe_validation_error(error),
)
async def http_error_handler(request: Request, error: Exception) -> JSONResponse:
"""Ошибки маршрутизации неизвестный путь, неподдерживаемый метод"""
assert isinstance(error, StarletteHTTPException)
if error.status_code == HTTPStatus.NOT_FOUND:
code, message = NotFoundError.code, NotFoundError.default_message
elif error.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR:
code, message = AppError.code, AppError.default_message
else:
code, message = ErrorCode.INVALID_REQUEST, HTTPStatus(error.status_code).phrase
return error_response(
get_request_id(request), error.status_code, code, message, error.headers
)
def _describe_validation_error(error: RequestValidationError) -> str:
"""Безопасное описание: только тип и путь поля, без присланного значения"""
first = error.errors()[0]
if first.get("type") == "json_invalid":
return "Некорректный JSON в теле запроса"
location = ".".join(str(part) for part in first.get("loc", ()))
return f"Некорректное значение: {location}"
def register_exception_handlers(app: FastAPI) -> None:
app.add_exception_handler(AppError, app_error_handler)
app.add_exception_handler(RequestValidationError, validation_error_handler)
app.add_exception_handler(StarletteHTTPException, http_error_handler)