Coverage for fastapi/exception_handlers.py: 100%
17 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from fastapi.encoders import jsonable_encoder 1abcde
2from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError 1abcde
3from fastapi.utils import is_body_allowed_for_status_code 1abcde
4from fastapi.websockets import WebSocket 1abcde
5from starlette.exceptions import HTTPException 1abcde
6from starlette.requests import Request 1abcde
7from starlette.responses import JSONResponse, Response 1abcde
8from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION 1abcde
11async def http_exception_handler(request: Request, exc: HTTPException) -> Response: 1abcde
12 headers = getattr(exc, "headers", None) 1abcde
13 if not is_body_allowed_for_status_code(exc.status_code): 1abcde
14 return Response(status_code=exc.status_code, headers=headers) 1abcde
15 return JSONResponse( 1abcde
16 {"detail": exc.detail}, status_code=exc.status_code, headers=headers
17 )
20async def request_validation_exception_handler( 1abcde
21 request: Request, exc: RequestValidationError
22) -> JSONResponse:
23 return JSONResponse( 1abcde
24 status_code=HTTP_422_UNPROCESSABLE_ENTITY,
25 content={"detail": jsonable_encoder(exc.errors())},
26 )
29async def websocket_request_validation_exception_handler( 1abcde
30 websocket: WebSocket, exc: WebSocketRequestValidationError
31) -> None:
32 await websocket.close( 1abcde
33 code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())
34 )