You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

35 lines
1.3 KiB

  1. from fastapi.encoders import jsonable_encoder
  2. from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
  3. from fastapi.utils import is_body_allowed_for_status_code
  4. from fastapi.websockets import WebSocket
  5. from starlette.exceptions import HTTPException
  6. from starlette.requests import Request
  7. from starlette.responses import JSONResponse, Response
  8. from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION
  9. async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
  10. headers = getattr(exc, "headers", None)
  11. if not is_body_allowed_for_status_code(exc.status_code):
  12. return Response(status_code=exc.status_code, headers=headers)
  13. return JSONResponse(
  14. {"detail": exc.detail}, status_code=exc.status_code, headers=headers
  15. )
  16. async def request_validation_exception_handler(
  17. request: Request, exc: RequestValidationError
  18. ) -> JSONResponse:
  19. return JSONResponse(
  20. status_code=HTTP_422_UNPROCESSABLE_ENTITY,
  21. content={"detail": jsonable_encoder(exc.errors())},
  22. )
  23. async def websocket_request_validation_exception_handler(
  24. websocket: WebSocket, exc: WebSocketRequestValidationError
  25. ) -> None:
  26. await websocket.close(
  27. code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())
  28. )