Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Custom exception handler + await request.json() == hanging service #1909

Description

@jjbankert

Example

Run the code below and

  • trigger buggy behavior: curl -X POST "http://localhost:8000/" -H "accept: application/json" -H "Content-Type: application/json" -d "{}"
  • trigger expected behavior: curl -X POST "http://localhost:8000/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"msg\":\"string\"}"
import fastapi
import pydantic
from fastapi.exception_handlers import (
    request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError

app = fastapi.FastAPI()


class BodyModel(pydantic.BaseModel):
    msg: str


@app.exception_handler(RequestValidationError)
async def log_request_validation_error(request, exception):
    try:
        body = await request.json()  # this will enter an infinite loop
        print(f"Invalid body: {body}")

    except Exception:  # this doesn't get triggered
        pass

    return await request_validation_exception_handler(request, exception)


@app.post('/')
async def endpoint(body: BodyModel, request: fastapi.Request):
    request_body = await request.json()  # just to show that parsing the request json is fine here
    print(f"valid body: {request_body}")

    return body


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

Description

Executing await request.json() in a method that's annotated @app.exception_handler(MyException) leads to the service hanging.

The goal of executing this function is to log the exact request parameters that lead to an error. So if there's a better way inside this exception handler to get the body parameters then that would be welcome.

Environment

  • OS: CentOS7
  • FastAPI Version: encountered on 0.52.0 and 0.61.0
  • Python version: 3.8

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions