error_responses.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from typing import List
  2. from typing import Union
  3. from fastapi.encoders import jsonable_encoder
  4. from fastapi.requests import Request
  5. from fastapi.responses import JSONResponse
  6. from starlette import status
  7. from clean_python.base.domain.exceptions import BadRequest
  8. from clean_python.base.domain.exceptions import Conflict
  9. from clean_python.base.domain.exceptions import DoesNotExist
  10. from clean_python.base.domain.exceptions import PermissionDenied
  11. from clean_python.base.domain.exceptions import Unauthorized
  12. from clean_python.base.domain.value_object import ValueObject
  13. __all__ = [
  14. "ValidationErrorResponse",
  15. "DefaultErrorResponse",
  16. "not_found_handler",
  17. "conflict_handler",
  18. "validation_error_handler",
  19. "not_implemented_handler",
  20. "permission_denied_handler",
  21. "unauthorized_handler",
  22. ]
  23. class ValidationErrorEntry(ValueObject):
  24. loc: List[Union[str, int]]
  25. msg: str
  26. type: str
  27. class ValidationErrorResponse(ValueObject):
  28. detail: List[ValidationErrorEntry]
  29. class DefaultErrorResponse(ValueObject):
  30. message: str
  31. async def not_found_handler(request: Request, exc: DoesNotExist):
  32. return JSONResponse(
  33. status_code=status.HTTP_404_NOT_FOUND,
  34. content={"message": f"Could not find {exc.name} with id={exc.id}"},
  35. )
  36. async def conflict_handler(request: Request, exc: Conflict):
  37. return JSONResponse(
  38. status_code=status.HTTP_409_CONFLICT,
  39. content={"message": str(exc)},
  40. )
  41. async def validation_error_handler(request: Request, exc: BadRequest):
  42. return JSONResponse(
  43. status_code=status.HTTP_400_BAD_REQUEST,
  44. content=jsonable_encoder({"detail": exc.errors()}),
  45. )
  46. async def not_implemented_handler(request: Request, exc: NotImplementedError):
  47. return JSONResponse(
  48. status_code=status.HTTP_501_NOT_IMPLEMENTED,
  49. content={"message": str(exc)},
  50. )
  51. async def unauthorized_handler(request: Request, exc: Unauthorized):
  52. return JSONResponse(
  53. status_code=status.HTTP_401_UNAUTHORIZED,
  54. content={"message": "Unauthorized"},
  55. )
  56. async def permission_denied_handler(request: Request, exc: PermissionDenied):
  57. return JSONResponse(
  58. status_code=status.HTTP_403_FORBIDDEN,
  59. content={"message": "Permission denied"},
  60. )