Performance: Global exception middleware
MEDIUM IMPACT
This affects server response time and user experience by handling errors centrally without repeating code.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def global_exception_handler(request: Request, call_next): try: response = await call_next(request) return response except Exception as exc: return JSONResponse(status_code=500, content={"detail": "Internal Server Error"}) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: raise ValueError("Invalid item id") return {"item_id": item_id}
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Per-route error handling | N/A (server-side) | N/A | N/A | [!] OK |
| Global exception middleware | N/A (server-side) | N/A | N/A | [OK] Good |