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

Skip to content

Preserve json.JSONDecodeError when handling invalid JSON in request body #3993

@declaresub

Description

@declaresub

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

not applicable

Description

I think that the response to a request with syntactically invalid JSON should be 400, not 422. This is the feature request I would prefer. But I would be willing to write a custom exception handler for now, if that were feasible.

Wanted Solution

In FastAPI/routing.py line 210-211, we have

    except json.JSONDecodeError as e:
        raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc)

I propose that the original exception not be discarded, by raising from --

    except json.JSONDecodeError as e:
        raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc) from e

With the original exception included, it would be simple enough to write a custom exception handler to handle the request as I see fit. This change should not break anyone's code, and I think it is generally the better practice to use raise from in such situations.

Wanted Code

not applicable

Alternatives

No response

Operating System

Linux, macOS

Operating System Details

No response

FastAPI Version

0.63.0

Python Version

3.9.5

Additional Context

No response

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