forked from mtusi2026/mtusi2026lab2
fix: 503 при сбое зависимостей, таймаут пула pg, сохранение NUL символа в сообщениях
This commit is contained in:
+50
-2
@@ -1,11 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
import redis.exceptions
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
|
||||
@@ -15,6 +16,10 @@ class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnavailableError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRequestError(StorageError):
|
||||
pass
|
||||
|
||||
@@ -154,11 +159,54 @@ def register_error_handlers(app: FastAPI) -> None:
|
||||
exc.status_code, code, msg, req_id, headers=extra_headers
|
||||
)
|
||||
|
||||
async def dependency_unavailable_handler(
|
||||
request: Request, exc: Exception
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
logger.warning(
|
||||
"Upstream storage dependency unavailable for request %s: %s",
|
||||
req_id,
|
||||
exc,
|
||||
)
|
||||
return make_error_response(
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
ErrorCode.UNAVAILABLE,
|
||||
"Зависимость недоступна",
|
||||
req_id,
|
||||
)
|
||||
|
||||
for exc_cls in (
|
||||
UnavailableError,
|
||||
asyncpg.PostgresError,
|
||||
asyncpg.InterfaceError,
|
||||
redis.exceptions.RedisError,
|
||||
TimeoutError,
|
||||
asyncio.TimeoutError,
|
||||
ConnectionError,
|
||||
OSError,
|
||||
):
|
||||
app.add_exception_handler(exc_cls, dependency_unavailable_handler)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(
|
||||
request: Request, exc: Exception
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
if isinstance(
|
||||
exc,
|
||||
(
|
||||
UnavailableError,
|
||||
asyncpg.PostgresError,
|
||||
asyncpg.InterfaceError,
|
||||
redis.exceptions.RedisError,
|
||||
TimeoutError,
|
||||
asyncio.TimeoutError,
|
||||
ConnectionError,
|
||||
OSError,
|
||||
),
|
||||
):
|
||||
return await dependency_unavailable_handler(request, exc)
|
||||
|
||||
logger.error(
|
||||
"Unhandled exception for request %s: %s", req_id, exc, exc_info=True
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user