Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /londarks_fastapi-flare /src /fastapi_flare /handlers.py
| """Exception handlers for fastapi-flare.""" | |
| from __future__ import annotations | |
| import json | |
| import time | |
| import traceback | |
| from typing import TYPE_CHECKING, Any, Optional | |
| from fastapi import Request | |
| from fastapi.encoders import jsonable_encoder | |
| from fastapi.exceptions import HTTPException, RequestValidationError | |
| from fastapi.responses import JSONResponse | |
| if TYPE_CHECKING: | |
| from fastapi_flare.config import FlareConfig | |
| def _duration_ms(request: Request) -> int | None: | |
| start = getattr(request.state, "start_time", None) | |
| if start is None: | |
| return None | |
| return int((time.monotonic() - start) * 1000) | |
| def _client_ip(request: Request) -> str | None: | |
| if request.client: | |
| return request.client.host | |
| return None | |
| def _endpoint(request: Request) -> str: | |
| """Return the matched route template (e.g. ``/items/{id}``) when available, | |
| falling back to the literal request path. | |
| Using the template here lets the issue-fingerprint collapse all UUID | |
| variations of the same endpoint into a single issue, instead of producing | |
| one row per concrete path. The literal URL is still preserved on the | |
| request entry in ``flare_requests`` for drill-down. | |
| """ | |
| route = request.scope.get("route") | |
| if route is not None and getattr(route, "path", None): | |
| return route.path | |
| return request.url.path | |
| def _capture_response_payload( | |
| config: "FlareConfig", status_code: int, payload: Any | |
| ) -> Any: | |
| """Return *payload* when response-body capture is on and status meets threshold. | |
| Centralised here so each handler respects the same opt-in rules. | |
| """ | |
| if not getattr(config, "capture_response_body", False): | |
| return None | |
| min_status = int(getattr(config, "capture_response_body_min_status", 400) or 0) | |
| if status_code < min_status: | |
| return None | |
| return payload | |
| # Key used by BodyCacheMiddleware to store raw bytes in the request scope. | |
| # All Request objects for the same HTTP transaction share the same scope dict, | |
| # so any handler can read this key even after the receive() stream is exhausted. | |
| _SCOPE_BODY_KEY = "_flare_body" | |
| async def _request_body(request: Request, config: "FlareConfig") -> Optional[Any]: | |
| """Read and return the decoded request body for non-GET methods. | |
| Resolution order: | |
| 1. ``scope["_flare_body"]`` — set by ``BodyCacheMiddleware`` before the | |
| inner app (FastAPI / Pydantic) consumes the ASGI receive() stream. | |
| Exception handlers receive a *fresh* ``Request`` object whose ``_body`` | |
| attribute is not yet populated, but they share the same ``scope`` dict, | |
| so the cache is always accessible. | |
| 2. ``request.body()`` — fallback for requests not handled by our middleware | |
| (e.g. direct TestClient calls or third-party integrations). | |
| Other rules: | |
| - Skipped for GET / HEAD / OPTIONS (no body). | |
| - Capped at ``config.max_request_body_bytes`` (0 = disabled). | |
| - Tries JSON decode first; falls back to a plain string. | |
| - Returns ``None`` on any failure or when disabled. | |
| """ | |
| if config.max_request_body_bytes <= 0: | |
| return None | |
| if request.method in ("GET", "HEAD", "OPTIONS"): | |
| return None | |
| try: | |
| # 1. Scope cache (fastest path — populated by BodyCacheMiddleware) | |
| raw: bytes = request.scope.get(_SCOPE_BODY_KEY) or b"" | |
| # 2. Fallback: try reading directly (works when receive() is not exhausted) | |
| if not raw: | |
| raw = await request.body() | |
| if raw: | |
| # Store in scope so any subsequent call on the same transaction | |
| # can retrieve it without re-reading the stream. | |
| request.scope[_SCOPE_BODY_KEY] = raw | |
| if not raw: | |
| return None | |
| raw = raw[: config.max_request_body_bytes] | |
| try: | |
| decoded = raw.decode("utf-8", errors="replace") | |
| return json.loads(decoded) | |
| except (json.JSONDecodeError, ValueError): | |
| return raw.decode("utf-8", errors="replace") | |
| except Exception: | |
| return None | |
| def make_http_exception_handler(config: "FlareConfig"): | |
| """ | |
| Handler for FastAPI's HTTPException. | |
| Logs ALL 4xx and 5xx responses — including 422 raised manually. | |
| """ | |
| async def handler(request: Request, exc: HTTPException) -> JSONResponse: | |
| from fastapi_flare.queue import push_log | |
| response_payload = {"detail": exc.detail} | |
| if exc.status_code >= 400: | |
| level = "ERROR" if exc.status_code >= 500 else "WARNING" | |
| body = await _request_body(request, config) | |
| await push_log( | |
| config, | |
| level=level, | |
| event="http_exception", | |
| message=str(exc.detail), | |
| request_id=getattr(request.state, "request_id", None), | |
| endpoint=_endpoint(request), | |
| http_method=request.method, | |
| http_status=exc.status_code, | |
| ip_address=_client_ip(request), | |
| duration_ms=_duration_ms(request), | |
| error=f"HTTPException {exc.status_code}: {exc.detail}", | |
| request_body=body, | |
| response_body=_capture_response_payload(config, exc.status_code, response_payload), | |
| ) | |
| return JSONResponse(status_code=exc.status_code, content=response_payload) | |
| return handler | |
| def make_generic_exception_handler(config: "FlareConfig"): | |
| """ | |
| Handler for all unhandled Python exceptions (500). | |
| Captures the full traceback and the request body. | |
| """ | |
| async def handler(request: Request, exc: Exception) -> JSONResponse: | |
| from fastapi_flare.queue import push_log | |
| tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__) | |
| tb_str = "".join(tb_lines) | |
| body = await _request_body(request, config) | |
| response_payload = {"detail": "Internal server error"} | |
| await push_log( | |
| config, | |
| level="ERROR", | |
| event="unhandled_exception", | |
| message=str(exc), | |
| request_id=getattr(request.state, "request_id", None), | |
| endpoint=_endpoint(request), | |
| http_method=request.method, | |
| http_status=500, | |
| ip_address=_client_ip(request), | |
| duration_ms=_duration_ms(request), | |
| error=f"{type(exc).__name__}: {str(exc)}", | |
| stack_trace=tb_str, | |
| request_body=body, | |
| response_body=_capture_response_payload(config, 500, response_payload), | |
| ) | |
| return JSONResponse(status_code=500, content=response_payload) | |
| return handler | |
| def make_validation_exception_handler(config: "FlareConfig"): | |
| """ | |
| Handler for Pydantic RequestValidationError (HTTP 422). | |
| FastAPI raises this automatically when request data fails schema | |
| validation. Logs as WARNING with: | |
| - A human-readable summary of every violated field. | |
| - The raw request body that triggered the error. | |
| """ | |
| async def handler(request: Request, exc: RequestValidationError) -> JSONResponse: | |
| from fastapi_flare.queue import push_log | |
| # Pydantic v2 embeds the raw exception object in ctx (e.g. a ValueError | |
| # raised inside a field_validator), which json.dumps cannot serialize. | |
| errors = jsonable_encoder(exc.errors(), custom_encoder={Exception: str}) | |
| # Build a concise human-readable error string | |
| parts = [] | |
| for e in errors: | |
| loc = " -> ".join(str(l) for l in e.get("loc", [])) | |
| msg = e.get("msg", "") | |
| parts.append(f"{loc}: {msg}" if loc else msg) | |
| error_summary = " | ".join(parts) if parts else "Validation failed" | |
| first_msg = parts[0] if parts else "Request validation failed" | |
| # Prefer exc.body (already parsed by FastAPI) over re-reading raw bytes | |
| body: Any = getattr(exc, "body", None) | |
| if body is None: | |
| body = await _request_body(request, config) | |
| elif isinstance(body, (dict, list)): | |
| pass # already decoded | |
| elif isinstance(body, bytes): | |
| try: | |
| body = json.loads(body.decode("utf-8", errors="replace")) | |
| except Exception: | |
| body = body.decode("utf-8", errors="replace") | |
| response_payload = {"detail": errors} | |
| await push_log( | |
| config, | |
| level="WARNING", | |
| event="validation_error", | |
| message=first_msg, | |
| request_id=getattr(request.state, "request_id", None), | |
| endpoint=_endpoint(request), | |
| http_method=request.method, | |
| http_status=422, | |
| ip_address=_client_ip(request), | |
| duration_ms=_duration_ms(request), | |
| error=error_summary, | |
| request_body=body, | |
| response_body=_capture_response_payload(config, 422, response_payload), | |
| ) | |
| return JSONResponse(status_code=422, content=response_payload) | |
| return handler | |
Xet Storage Details
- Size:
- 8.99 kB
- Xet hash:
- 9c540777aaf08acc89eba213818b8f4d517590819244f43a6e052c659c8b90ef
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.