2026-02-09 15:49:50 +05:30
|
|
|
"""Global exception handlers and request-id middleware for FastAPI."""
|
|
|
|
|
|
2026-02-07 03:14:30 +05:30
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
from collections.abc import Awaitable, Callable
|
2026-02-09 20:40:17 +05:30
|
|
|
from typing import TYPE_CHECKING, Any, Final
|
2026-02-07 03:14:30 +05:30
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
|
|
from fastapi import FastAPI, Request
|
|
|
|
|
from fastapi.exceptions import RequestValidationError, ResponseValidationError
|
|
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
|
from starlette.responses import Response
|
2026-02-09 15:49:50 +05:30
|
|
|
|
2026-02-09 20:44:05 +05:30
|
|
|
if TYPE_CHECKING: # pragma: no cover
|
2026-02-09 15:49:50 +05:30
|
|
|
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
2026-02-07 03:14:30 +05:30
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
REQUEST_ID_HEADER: Final[str] = "X-Request-Id"
|
|
|
|
|
|
|
|
|
|
ExceptionHandler = Callable[[Request, Exception], Response | Awaitable[Response]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RequestIdMiddleware:
|
2026-02-09 15:49:50 +05:30
|
|
|
"""ASGI middleware that ensures every request has a request-id."""
|
|
|
|
|
|
2026-02-07 03:14:30 +05:30
|
|
|
def __init__(self, app: ASGIApp, *, header_name: str = REQUEST_ID_HEADER) -> None:
|
2026-02-09 15:49:50 +05:30
|
|
|
"""Initialize middleware with app instance and header name."""
|
2026-02-07 03:14:30 +05:30
|
|
|
self._app = app
|
|
|
|
|
self._header_name = header_name
|
|
|
|
|
self._header_name_bytes = header_name.lower().encode("latin-1")
|
|
|
|
|
|
|
|
|
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
2026-02-09 15:49:50 +05:30
|
|
|
"""Inject request-id into request state and response headers."""
|
2026-02-07 03:14:30 +05:30
|
|
|
if scope["type"] != "http":
|
|
|
|
|
await self._app(scope, receive, send)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
request_id = self._get_or_create_request_id(scope)
|
|
|
|
|
|
|
|
|
|
async def send_with_request_id(message: Message) -> None:
|
|
|
|
|
if message["type"] == "http.response.start":
|
|
|
|
|
# Starlette uses `list[tuple[bytes, bytes]]` here.
|
|
|
|
|
headers: list[tuple[bytes, bytes]] = message.setdefault("headers", [])
|
2026-02-09 20:44:05 +05:30
|
|
|
if not any(key.lower() == self._header_name_bytes for key, _ in headers):
|
2026-02-09 15:49:50 +05:30
|
|
|
request_id_bytes = request_id.encode("latin-1")
|
|
|
|
|
headers.append((self._header_name_bytes, request_id_bytes))
|
2026-02-07 03:14:30 +05:30
|
|
|
await send(message)
|
|
|
|
|
|
|
|
|
|
await self._app(scope, receive, send_with_request_id)
|
|
|
|
|
|
|
|
|
|
def _get_or_create_request_id(self, scope: Scope) -> str:
|
|
|
|
|
# Accept a client-provided request id if present.
|
|
|
|
|
request_id: str | None = None
|
|
|
|
|
for key, value in scope.get("headers", []):
|
|
|
|
|
if key.lower() == self._header_name_bytes:
|
|
|
|
|
candidate = value.decode("latin-1").strip()
|
|
|
|
|
if candidate:
|
|
|
|
|
request_id = candidate
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
if request_id is None:
|
|
|
|
|
request_id = uuid4().hex
|
|
|
|
|
|
|
|
|
|
# `Request.state` is backed by `scope["state"]`.
|
|
|
|
|
state = scope.setdefault("state", {})
|
|
|
|
|
state["request_id"] = request_id
|
|
|
|
|
return request_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def install_error_handling(app: FastAPI) -> None:
|
2026-02-09 15:49:50 +05:30
|
|
|
"""Install middleware and exception handlers on the FastAPI app."""
|
2026-02-07 03:14:30 +05:30
|
|
|
# Important: add request-id middleware last so it's the outermost middleware.
|
2026-02-09 15:49:50 +05:30
|
|
|
# This ensures it still runs even if another middleware
|
|
|
|
|
# (e.g. CORS preflight) returns early.
|
2026-02-07 03:14:30 +05:30
|
|
|
app.add_middleware(RequestIdMiddleware)
|
|
|
|
|
|
|
|
|
|
app.add_exception_handler(
|
|
|
|
|
RequestValidationError,
|
2026-02-09 20:40:17 +05:30
|
|
|
_request_validation_exception_handler,
|
2026-02-07 03:14:30 +05:30
|
|
|
)
|
|
|
|
|
app.add_exception_handler(
|
|
|
|
|
ResponseValidationError,
|
2026-02-09 20:40:17 +05:30
|
|
|
_response_validation_exception_handler,
|
2026-02-07 03:14:30 +05:30
|
|
|
)
|
|
|
|
|
app.add_exception_handler(
|
|
|
|
|
StarletteHTTPException,
|
2026-02-09 20:40:17 +05:30
|
|
|
_http_exception_exception_handler,
|
2026-02-07 03:14:30 +05:30
|
|
|
)
|
|
|
|
|
app.add_exception_handler(Exception, _unhandled_exception_handler)
|
|
|
|
|
|
|
|
|
|
|
2026-02-09 20:40:17 +05:30
|
|
|
async def _request_validation_exception_handler(
|
|
|
|
|
request: Request,
|
|
|
|
|
exc: Exception,
|
|
|
|
|
) -> Response:
|
|
|
|
|
if not isinstance(exc, RequestValidationError):
|
|
|
|
|
msg = "Expected RequestValidationError"
|
|
|
|
|
raise TypeError(msg)
|
|
|
|
|
return await _request_validation_handler(request, exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _response_validation_exception_handler(
|
|
|
|
|
request: Request,
|
|
|
|
|
exc: Exception,
|
|
|
|
|
) -> Response:
|
|
|
|
|
if not isinstance(exc, ResponseValidationError):
|
|
|
|
|
msg = "Expected ResponseValidationError"
|
|
|
|
|
raise TypeError(msg)
|
|
|
|
|
return await _response_validation_handler(request, exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _http_exception_exception_handler(
|
|
|
|
|
request: Request,
|
|
|
|
|
exc: Exception,
|
|
|
|
|
) -> Response:
|
|
|
|
|
if not isinstance(exc, StarletteHTTPException):
|
|
|
|
|
msg = "Expected StarletteHTTPException"
|
|
|
|
|
raise TypeError(msg)
|
|
|
|
|
return await _http_exception_handler(request, exc)
|
|
|
|
|
|
|
|
|
|
|
2026-02-07 03:14:30 +05:30
|
|
|
def _get_request_id(request: Request) -> str | None:
|
|
|
|
|
request_id = getattr(request.state, "request_id", None)
|
|
|
|
|
if isinstance(request_id, str) and request_id:
|
|
|
|
|
return request_id
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
2026-02-09 15:49:50 +05:30
|
|
|
def _error_payload(*, detail: object, request_id: str | None) -> dict[str, object]:
|
2026-02-07 03:14:30 +05:30
|
|
|
payload: dict[str, Any] = {"detail": detail}
|
|
|
|
|
if request_id:
|
|
|
|
|
payload["request_id"] = request_id
|
|
|
|
|
return payload
|
|
|
|
|
|
|
|
|
|
|
2026-02-07 03:40:28 +05:30
|
|
|
async def _request_validation_handler(
|
2026-02-09 15:49:50 +05:30
|
|
|
request: Request,
|
|
|
|
|
exc: RequestValidationError,
|
2026-02-07 03:40:28 +05:30
|
|
|
) -> JSONResponse:
|
2026-02-07 03:14:30 +05:30
|
|
|
# `RequestValidationError` is expected user input; don't log at ERROR.
|
|
|
|
|
request_id = _get_request_id(request)
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=422,
|
|
|
|
|
content=_error_payload(detail=exc.errors(), request_id=request_id),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-02-07 03:40:28 +05:30
|
|
|
async def _response_validation_handler(
|
2026-02-09 15:49:50 +05:30
|
|
|
request: Request,
|
|
|
|
|
exc: ResponseValidationError,
|
2026-02-07 03:40:28 +05:30
|
|
|
) -> JSONResponse:
|
2026-02-07 03:14:30 +05:30
|
|
|
request_id = _get_request_id(request)
|
|
|
|
|
logger.exception(
|
|
|
|
|
"response_validation_error",
|
|
|
|
|
extra={
|
|
|
|
|
"request_id": request_id,
|
|
|
|
|
"method": request.method,
|
|
|
|
|
"path": request.url.path,
|
|
|
|
|
"errors": exc.errors(),
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=500,
|
|
|
|
|
content=_error_payload(detail="Internal Server Error", request_id=request_id),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-02-09 15:49:50 +05:30
|
|
|
async def _http_exception_handler(
|
|
|
|
|
request: Request,
|
|
|
|
|
exc: StarletteHTTPException,
|
|
|
|
|
) -> JSONResponse:
|
2026-02-07 03:14:30 +05:30
|
|
|
request_id = _get_request_id(request)
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=exc.status_code,
|
|
|
|
|
content=_error_payload(detail=exc.detail, request_id=request_id),
|
|
|
|
|
headers=exc.headers,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-02-09 15:49:50 +05:30
|
|
|
async def _unhandled_exception_handler(
|
|
|
|
|
request: Request,
|
|
|
|
|
_exc: Exception,
|
|
|
|
|
) -> JSONResponse:
|
2026-02-07 03:14:30 +05:30
|
|
|
request_id = _get_request_id(request)
|
|
|
|
|
logger.exception(
|
|
|
|
|
"unhandled_exception",
|
2026-02-09 15:49:50 +05:30
|
|
|
extra={
|
|
|
|
|
"request_id": request_id,
|
|
|
|
|
"method": request.method,
|
|
|
|
|
"path": request.url.path,
|
|
|
|
|
},
|
2026-02-07 03:14:30 +05:30
|
|
|
)
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=500,
|
|
|
|
|
content=_error_payload(detail="Internal Server Error", request_id=request_id),
|
|
|
|
|
headers={REQUEST_ID_HEADER: request_id} if request_id else None,
|
|
|
|
|
)
|