forked from mtusi2026/mtusi2026lab3
62 lines
2.6 KiB
Python
62 lines
2.6 KiB
Python
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,
|
|
error.headers,
|
|
)
|
|
|
|
|
|
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)
|