Skip to content

Validation exceptions hidden in RuntimeErrors #145

@stdweird

Description

@stdweird

the current validation_exception_handler calls request.body() as the first thing, but unless there is caching/buffering implemented in the middleware, calling the .body() a 2nd time (eg middleware calls it first, and then 2nd time in the validation exception handler) this will raise a RuntimeException with Stream consumed message. and thus hiding the real issue of the validation error.

ideally modify the code by moving the logger.debug with some non-body related info before the .body() is called will help debuggin the underlying problem. e.g.

@app.exception_handler(RequestValidationError)                                                                                                                                               
async def validation_exception_handler(request: Request, exc: RequestValidationError):                                                                                                       
    logger.debug(f"Validation error occurred {request.url=} {exc=}")                                                                                                                         
    logger.debug(f"Validation errors: {exc.errors()}")                                                                                                                                       
    body = await request.body()     
    ...

implementing the buffering and thus avoiding the RuntimeException is also possible ofcourse (see eg Kludex/starlette#2556).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions