from fastapi import FastAPI, HTTPException, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse def register_exception_handlers(app: FastAPI) -> None: @app.exception_handler(RequestValidationError) async def request_validation_exception_handler(_: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()}, ) @app.exception_handler(HTTPException) async def http_exception_handler(_: Request, exc: HTTPException): # Не ломаем существующие ответы endpoint-ов и прокидываем исходный detail. return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail}, headers=exc.headers, ) @app.exception_handler(Exception) async def unhandled_exception_handler(_: Request, exc: Exception): return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "внутренняя ошибка сервера"}, )