Performance: Global exception middleware
This affects server response time and user experience by handling errors centrally without repeating code.
Jump into concepts and practice - no test required
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 |
add_middleware method to add middleware.add_middleware is valid; others are incorrect method names.from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.middleware("http")
async def catch_exceptions_middleware(request: Request, call_next):
try:
response = await call_next(request)
return response
except ValueError as e:
return JSONResponse(status_code=400, content={"error": str(e)})
@app.get("/test")
async def test_route():
raise ValueError("Invalid input")from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.middleware("http")
async def exception_middleware(request: Request, call_next):
try:
response = call_next(request)
return response
except Exception as e:
return JSONResponse(status_code=500, content={"error": "Server error"})