|
2 | 2 |
|
3 | 3 | from starlette.applications import Starlette |
4 | 4 | from starlette.exceptions import HTTPException |
| 5 | +from starlette.middleware import Middleware |
5 | 6 | from starlette.middleware.base import ( |
6 | 7 | BaseHTTPMiddleware, |
7 | 8 | RequestResponseEndpoint, |
|
14 | 15 | from examples.example_with_exception_handling.logger import log |
15 | 16 | from starlette_context import middleware, plugins |
16 | 17 |
|
17 | | -app = Starlette(debug=True) |
18 | | - |
19 | | - |
20 | | -@app.route("/") |
21 | | -async def index(request: Request): |
22 | | - log.info("pre exception") |
23 | | - _ = 1 / 0 |
24 | | - return JSONResponse({"wont reach this place": None}) |
25 | | - |
26 | 18 |
|
27 | 19 | class ExceptionHandlingMiddleware(BaseHTTPMiddleware): |
28 | 20 | @staticmethod |
@@ -54,15 +46,28 @@ async def dispatch( |
54 | 46 |
|
55 | 47 |
|
56 | 48 | # middleware order is important! exc handler has to be topmost |
| 49 | +middleware = [ |
| 50 | + Middleware( |
| 51 | + middleware.ContextMiddleware, |
| 52 | + plugins=( |
| 53 | + plugins.CorrelationIdPlugin(), |
| 54 | + plugins.RequestIdPlugin(), |
| 55 | + plugins.DateHeaderPlugin(), |
| 56 | + plugins.ForwardedForPlugin(), |
| 57 | + plugins.UserAgentPlugin(), |
| 58 | + ), |
| 59 | + ), |
| 60 | + Middleware(ExceptionHandlingMiddleware), |
| 61 | +] |
| 62 | + |
| 63 | +app = Starlette(debug=True, middleware=middleware) |
| 64 | + |
| 65 | + |
| 66 | +@app.route("/") |
| 67 | +async def index(request: Request): |
| 68 | + log.info("pre exception") |
| 69 | + _ = 1 / 0 |
| 70 | + return JSONResponse({"wont reach this place": None}) |
| 71 | + |
57 | 72 |
|
58 | | -app.add_middleware(ExceptionHandlingMiddleware) |
59 | | -app.add_middleware( |
60 | | - middleware.ContextMiddleware.with_plugins( |
61 | | - plugins.UserAgentPlugin, |
62 | | - plugins.ForwardedForPlugin, |
63 | | - plugins.DateHeaderPlugin, |
64 | | - plugins.RequestIdPlugin, |
65 | | - plugins.CorrelationIdPlugin, |
66 | | - ) |
67 | | -) |
68 | 73 | uvicorn.run(app, host="0.0.0.0") |
0 commit comments