Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

50 lignes
1.6 KiB

  1. from collections.abc import Iterable
  2. from fastapi.openapi.constants import REF_PREFIX
  3. from fastapi.openapi.utils import (
  4. validation_error_definition,
  5. validation_error_response_definition,
  6. )
  7. from starlette.exceptions import HTTPException
  8. from starlette.requests import Request
  9. from starlette.responses import JSONResponse
  10. from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
  11. async def http_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
  12. return JSONResponse({"errors": [exc.detail]}, status_code=exc.status_code)
  13. async def http_422_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
  14. """
  15. Handler for 422 error to transform default pydantic error object to gothinkster format
  16. """
  17. errors = {"body": []}
  18. if isinstance(exc.detail, Iterable) and not isinstance(
  19. exc.detail, str
  20. ): # check if error is pydantic's model error
  21. for error in exc.detail:
  22. error_name = ".".join(
  23. error["loc"][1:]
  24. ) # remove 'body' from path to invalid element
  25. errors["body"].append({error_name: error["msg"]})
  26. else:
  27. errors["body"].append(exc.detail)
  28. return JSONResponse({"errors": errors}, status_code=HTTP_422_UNPROCESSABLE_ENTITY)
  29. # validation_error_definition["properties"] = {
  30. # "body": {"title": "Body", "type": "array", "items": {"type": "string"}}
  31. # }
  32. #
  33. # validation_error_response_definition["properties"] = {
  34. # "errors": {
  35. # "title": "Errors",
  36. # "type": "array",
  37. # "items": {"$ref": REF_PREFIX + "ValidationError"},
  38. # }
  39. # }