Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Preserve json.JSONDecodeError information when handling invalid JSON in request body, to support custom exception handlers that use its information #4057

Merged
merged 3 commits into from
Aug 25, 2022

Conversation

UKnowWhoIm
Copy link
Contributor

@UKnowWhoIm UKnowWhoIm commented Oct 16, 2021

Save JSONDecodeError to context by adding a from clause. The feature was requested because the user wants to use status code 400 for invalid response body.

Usage

from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def handle(request: Request, exc: Exception):
    if isinstance(exc.__context__, JSONDecodeError):
        return Response(str(exc),status_code=400)
    return await request_validation_exception_handler(request, exc)

Enhancement requested #3993

@tiangolo tiangolo changed the title Preserve json.JSONDecodeError when handling invalid JSON in request body ✨ Preserve json.JSONDecodeError information when handling invalid JSON in request body, to support custom exception handlers that use its information Aug 25, 2022
@codecov
Copy link

codecov bot commented Aug 25, 2022

Codecov Report

Merging #4057 (9809b51) into master (afaa039) will not change coverage.
The diff coverage is 100.00%.

@@            Coverage Diff            @@
##            master     #4057   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          533       533           
  Lines        13755     13755           
=========================================
  Hits         13755     13755           
Impacted Files Coverage Δ
fastapi/routing.py 100.00% <100.00%> (ø)

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@github-actions
Copy link
Contributor

📝 Docs preview for commit 9809b51 at: https://630746e846ee066d37855789--fastapi.netlify.app

@tiangolo
Copy link
Member

Awesome, thank you @UKnowWhoIm! 🙇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants