Browse Source

Add docstrings to default exception handler functions

The public exception handlers in fastapi/exception_handlers.py lacked
docstrings, making it harder to understand their behavior when overriding
them. Added concise docstrings to all three handlers.
pull/15011/head
Anandesh Sharma 5 months ago
parent
commit
5a0510bd6b
  1. 16
      fastapi/exception_handlers.py

16
fastapi/exception_handlers.py

@ -9,6 +9,12 @@ from starlette.status import WS_1008_POLICY_VIOLATION
async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
"""Default handler for `HTTPException`.
Returns a plain `Response` (no body) when the status code disallows a
response body (e.g. 204, 304), otherwise returns a JSON response with
the exception's `detail` field.
"""
headers = getattr(exc, "headers", None)
if not is_body_allowed_for_status_code(exc.status_code):
return Response(status_code=exc.status_code, headers=headers)
@ -20,6 +26,11 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> Respon
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
"""Default handler for `RequestValidationError`.
Returns a 422 JSON response whose body contains the list of validation
errors produced by Pydantic.
"""
return JSONResponse(
status_code=422,
content={"detail": jsonable_encoder(exc.errors())},
@ -29,6 +40,11 @@ async def request_validation_exception_handler(
async def websocket_request_validation_exception_handler(
websocket: WebSocket, exc: WebSocketRequestValidationError
) -> None:
"""Default handler for `WebSocketRequestValidationError`.
Closes the WebSocket connection with policy-violation code 1008 and
includes the validation errors in the close reason.
"""
await websocket.close(
code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())
)

Loading…
Cancel
Save