Chapter 22: Creating Custom Request Components
ASP.NET Core lets you build custom middleware, filters, model binders, and result types. FastAPI and Starlette let you build custom dependencies, middleware, routes, exception handlers, and response classes.
Custom exception mapping:
class RecipeNotFound(Exception):
def __init__(self, recipe_id: int):
self.recipe_id = recipe_id
@app.exception_handler(RecipeNotFound)
async def recipe_not_found_handler(request: Request, exc: RecipeNotFound):
return JSONResponse(
status_code=404,
content={"detail": f"Recipe {exc.recipe_id} was not found"},
)
Custom route behavior is powerful but should be rare. Prefer plain route functions, dependencies, and exception handlers. Framework extension points are for repeated infrastructure behavior, not for avoiding simple code.