diff --git a/fastapi/exception_handlers.py b/fastapi/exception_handlers.py index 2b286d71c7610..6c8db3d00aa45 100644 --- a/fastapi/exception_handlers.py +++ b/fastapi/exception_handlers.py @@ -1,13 +1,16 @@ from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError +from fastapi.utils import is_body_allowed_for_status_code from starlette.exceptions import HTTPException from starlette.requests import Request -from starlette.responses import JSONResponse +from starlette.responses import JSONResponse, Response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY -async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse: +async def http_exception_handler(request: Request, exc: HTTPException) -> Response: headers = getattr(exc, "headers", None) + if not is_body_allowed_for_status_code(exc.status_code): + return Response(status_code=exc.status_code, headers=exc.headers) if headers: return JSONResponse( {"detail": exc.detail}, status_code=exc.status_code, headers=headers