Files
mtusi2026lab2/app/errors.py
T

132 lines
4.7 KiB
Python

from __future__ import annotations
import logging
import uuid
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
from app.storage import (
ConflictError,
InvalidRequestError,
NotFoundError,
UnauthorizedError,
)
logger = logging.getLogger("app.errors")
def get_request_id(request: Request) -> str:
req_id = getattr(request.state, "request_id", None)
if not req_id:
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
return req_id
def make_error_response(
status_code: int, code: ErrorCode, message: str, request_id: str
) -> JSONResponse:
payload = ErrorResponse(
error=ErrorDetail(code=code, message=message, request_id=request_id)
).model_dump()
return JSONResponse(
status_code=status_code,
content=payload,
headers={"X-Request-Id": request_id, "Content-Type": "application/json"},
)
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(InvalidRequestError)
async def invalid_request_handler(
request: Request, exc: InvalidRequestError
) -> JSONResponse:
req_id = get_request_id(request)
return make_error_response(
status.HTTP_400_BAD_REQUEST, ErrorCode.INVALID_REQUEST, str(exc), req_id
)
@app.exception_handler(UnauthorizedError)
async def unauthorized_handler(
request: Request, exc: UnauthorizedError
) -> JSONResponse:
req_id = get_request_id(request)
return make_error_response(
status.HTTP_401_UNAUTHORIZED, ErrorCode.UNAUTHORIZED, str(exc), req_id
)
@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError) -> JSONResponse:
req_id = get_request_id(request)
return make_error_response(
status.HTTP_404_NOT_FOUND, ErrorCode.NOT_FOUND, str(exc), req_id
)
@app.exception_handler(ConflictError)
async def conflict_handler(request: Request, exc: ConflictError) -> JSONResponse:
req_id = get_request_id(request)
return make_error_response(
status.HTTP_409_CONFLICT, ErrorCode.CONFLICT, str(exc), req_id
)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
req_id = get_request_id(request)
# Ошибки валидации входного JSON маппятся на 400
errors = exc.errors()
messages = []
for err in errors:
loc = ".".join(str(x) for x in err.get("loc", []) if x != "body")
msg = err.get("msg", "invalid")
messages.append(f"{loc}: {msg}" if loc else msg)
detail_msg = "; ".join(messages) or "Некорректное тело запроса или параметры"
return make_error_response(
status.HTTP_400_BAD_REQUEST, ErrorCode.INVALID_REQUEST, detail_msg, req_id
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(
request: Request, exc: StarletteHTTPException
) -> JSONResponse:
req_id = get_request_id(request)
code = ErrorCode.INTERNAL_ERROR
if exc.status_code == 400:
code = ErrorCode.INVALID_REQUEST
elif exc.status_code == 401:
code = ErrorCode.UNAUTHORIZED
elif exc.status_code == 404:
code = ErrorCode.NOT_FOUND
elif exc.status_code == 409:
code = ErrorCode.CONFLICT
elif exc.status_code == 413:
code = ErrorCode.PAYLOAD_TOO_LARGE
elif exc.status_code == 415:
code = ErrorCode.UNSUPPORTED_MEDIA_TYPE
elif exc.status_code == 429:
code = ErrorCode.RATE_LIMITED
elif exc.status_code == 503:
code = ErrorCode.UNAVAILABLE
msg = exc.detail if isinstance(exc.detail, str) else "HTTP ошибка"
return make_error_response(exc.status_code, code, msg, req_id)
@app.exception_handler(Exception)
async def unhandled_exception_handler(
request: Request, exc: Exception
) -> JSONResponse:
req_id = get_request_id(request)
logger.error(
"Unhandled exception for request %s: %s", req_id, exc, exc_info=True
)
return make_error_response(
status.HTTP_500_INTERNAL_SERVER_ERROR,
ErrorCode.INTERNAL_ERROR,
"Внутренняя ошибка сервера",
req_id,
)