Add handler for RequestMalformedError exceptions

Added a new exception handler for RequestMalformedError to return a 400 status code with error details.
This commit is contained in:
Javier Sánchez Castro 2025-11-24 01:03:14 +01:00 committed by GitHub
parent a704d7e514
commit 4165d1cf6c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 10 additions and 1 deletions

View File

@ -1,5 +1,5 @@
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
from fastapi.exceptions import RequestMalformedError, RequestValidationError, WebSocketRequestValidationError
from fastapi.utils import is_body_allowed_for_status_code
from fastapi.websockets import WebSocket
from starlette.exceptions import HTTPException
@ -17,6 +17,15 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> Respon
)
async def request_malformed_exception_handler(
request: Request, exc: RequestMalformedError
) -> JSONResponse:
return JSONResponse(
status_code=400,
content={"detail": jsonable_encoder(exc.errors())},
)
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse: