You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi dears developers, how can I retrieve the request.body inside an exception_handler?
My scenario:
I have an exception_handler hook that receives a request and an exception, I'm also using FastApi which tries to parse the body to a JSON, if it does not work it raises an HTTPException. So I'm trying to build a hook to log invalid JSON requests, this exception is being correctly captured by my exception_handler but when I'm trying to retrieve the body I can't it hangs, it simple doesn't work. It does make sense as after reading for the first time it is being cached inside the Request object but the Request object is being recreated before calling the exception_handler so I'm losing my cache and I'm able to ready from the stream again.
Not sure if it is supposed to be like this by design, but I think my scenario is not that fancy, it should be something possible, what do you guys think? Any workaround?
My code:
async def httpexception_logger(request: Request, exc: HTTPException):
body = await request.body()
text: str = bytes.decode(body)
logger.error("Exception at %s, status code: %s, body: %s: exception %s", request.url, exception.status_code, text, exc)
... other stuff...
Reacted by Ankur Srivastava, Denis Kataev, Jordan Speizer, Nathaniel Sabanski, Ben Nutchanon Ninyawee, Brent Holmes, CQD, ., Peter Kong and Lukasz
Hi @tomchristie , I was able to reproduce with the code below:
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromstarlette.exceptionsimportHTTPExceptionfromjson.decoderimportJSONDecodeErrorimportuvicorn# Force an exception sending an invalid json to "/"# it will trigger an exception and it will be handled# by log_exceptions and the assert will trigger an# exception because request.body() cannot be read# anymore (stream already consumed)app=Starlette(debug=True)
@app.exception_handler(JSONDecodeError)asyncdeflog_exceptions(request, exc):
body: bytes=awaitrequest.body() # hangs foreverbody_text: str=bytes.decode(body)
assertbody_text, "I could not retrieve the body"returnJSONResponse({ "error": "Unexpected error happened!" })
@app.route('/', methods=["POST"])asyncdefhomepage(request):
body_bytes=awaitrequest.body()
ifbody_bytes:
json=awaitrequest.json()
returnJSONResponse(json)
returnJSONResponse({ "error": "empty body, please send something" })
if__name__=='__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
I have a very similar case running into the same problem:
Using FastAPI I would like to log requests and responses for requests that have triggered a HTTPException. My idea was to wrap FastAPIs existing http exception handler like so:
@tomchristie , I was reading your comments related to @blueyed changes to store the Request in the Scope and I completely agree that Request should reflect scope, and as scope is used to construct a request perhaps a small change to store/cache the body inside the scope instead of a local var, do you think this could solve this issue?
I did this changes locally just to test and it seems to work but I have not enough knowledge about the impact it may cause:
Activity
lovelydinosaur commentedon Apr 26, 2019
Whatβs the simplest possible code sample someone could use to replicate the issue? (Ideally just using Starlette itself if possible)
lovelydinosaur commentedon Apr 26, 2019
I expect thereβs an issue with the request body already having been streamed, but we ought to be able to handle things more gracefully.
ricardomomm commentedon Apr 29, 2019
Hi @tomchristie , I was able to reproduce with the code below:
to test:
gwdekker commentedon Apr 30, 2019
I have a very similar case running into the same problem:
Using FastAPI I would like to log requests and responses for requests that have triggered a HTTPException. My idea was to wrap FastAPIs existing http exception handler like so:
This hangs forever on the first line.
ansrivas commentedon Apr 30, 2019
#495 has this similar issue as well.
ricardomomm commentedon May 2, 2019
@tomchristie , I was reading your comments related to @blueyed changes to store the Request in the Scope and I completely agree that Request should reflect scope, and as scope is used to construct a request perhaps a small change to store/cache the body inside the scope instead of a local var, do you think this could solve this issue?
I did this changes locally just to test and it seems to work but I have not enough knowledge about the impact it may cause:
requests.py@140...171
Kludex#493 and Kludex#495 cache body content
kataev commentedon Sep 4, 2019
Any movements? Without this functionality, we don't have access to origin request on exception handler.
This is really strange.
tteguayco commentedon Mar 3, 2023
Any news? Still having the hanging issue.