Replies: 3 comments 1 reply
-
When I run your sample code I get the following
Which you would expect since If I correct for the error by refactoring your function to async def log_request(request: Request, call_next):
response = None
try:
response = await call_next(request)
except Exception:
logger.error("Middleware observed exception.")
response = Response(status_code=200, content="Caught in the middleware")
logger.info("Returning response.")
return response I get the expected 200 with the logged
This is with |
Beta Was this translation helpful? Give feedback.
-
@jgould22 Thank you very much! After upgrading to |
Beta Was this translation helpful? Give feedback.
-
HI guys! I have a question related to this one: what if I want to log the response body size that is returned from the exception handler? If |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I have this use case where I want to log the duration of all requests, this includes requests which crash the route handler function. For this I introduced a request logging middleware. From my observations once a exception handler is triggered, all middlewares are bypassed. So even if the exception handler returns an Response object there is no way to react to it in the middleware.
Is my understanding of this correct? And is this a bug or a feature?
(Based on the answer to do this I will submit an MR which adds this to the Middleware documentation)
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.70.1
Python Version
Python 3.10.0
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions