exceptions.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """
  2. Handled exceptions raised by REST framework.
  3. In addition Django's built in 403 and 404 exceptions are handled.
  4. (`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
  5. """
  6. import math
  7. from django.http import JsonResponse
  8. from django.utils.encoding import force_str
  9. from django.utils.translation import gettext_lazy as _
  10. from django.utils.translation import ngettext
  11. from rest_framework import status
  12. from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
  13. def _get_error_details(data, default_code=None):
  14. """
  15. Descend into a nested data structure, forcing any
  16. lazy translation strings or strings into `ErrorDetail`.
  17. """
  18. if isinstance(data, list):
  19. ret = [
  20. _get_error_details(item, default_code) for item in data
  21. ]
  22. if isinstance(data, ReturnList):
  23. return ReturnList(ret, serializer=data.serializer)
  24. return ret
  25. elif isinstance(data, dict):
  26. ret = {
  27. key: _get_error_details(value, default_code)
  28. for key, value in data.items()
  29. }
  30. if isinstance(data, ReturnDict):
  31. return ReturnDict(ret, serializer=data.serializer)
  32. return ret
  33. text = force_str(data)
  34. code = getattr(data, 'code', default_code)
  35. return ErrorDetail(text, code)
  36. def _get_codes(detail):
  37. if isinstance(detail, list):
  38. return [_get_codes(item) for item in detail]
  39. elif isinstance(detail, dict):
  40. return {key: _get_codes(value) for key, value in detail.items()}
  41. return detail.code
  42. def _get_full_details(detail):
  43. if isinstance(detail, list):
  44. return [_get_full_details(item) for item in detail]
  45. elif isinstance(detail, dict):
  46. return {key: _get_full_details(value) for key, value in detail.items()}
  47. return {
  48. 'message': detail,
  49. 'code': detail.code
  50. }
  51. class ErrorDetail(str):
  52. """
  53. A string-like object that can additionally have a code.
  54. """
  55. code = None
  56. def __new__(cls, string, code=None):
  57. self = super().__new__(cls, string)
  58. self.code = code
  59. return self
  60. def __eq__(self, other):
  61. r = super().__eq__(other)
  62. try:
  63. return r and self.code == other.code
  64. except AttributeError:
  65. return r
  66. def __ne__(self, other):
  67. return not self.__eq__(other)
  68. def __repr__(self):
  69. return 'ErrorDetail(string=%r, code=%r)' % (
  70. str(self),
  71. self.code,
  72. )
  73. def __hash__(self):
  74. return hash(str(self))
  75. class APIException(Exception):
  76. """
  77. Base class for REST framework exceptions.
  78. Subclasses should provide `.status_code` and `.default_detail` properties.
  79. """
  80. status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
  81. default_detail = _('A server error occurred.')
  82. default_code = 'error'
  83. def __init__(self, detail=None, code=None):
  84. if detail is None:
  85. detail = self.default_detail
  86. if code is None:
  87. code = self.default_code
  88. self.detail = _get_error_details(detail, code)
  89. def __str__(self):
  90. return str(self.detail)
  91. def get_codes(self):
  92. """
  93. Return only the code part of the error details.
  94. Eg. {"name": ["required"]}
  95. """
  96. return _get_codes(self.detail)
  97. def get_full_details(self):
  98. """
  99. Return both the message & code parts of the error details.
  100. Eg. {"name": [{"message": "This field is required.", "code": "required"}]}
  101. """
  102. return _get_full_details(self.detail)
  103. # The recommended style for using `ValidationError` is to keep it namespaced
  104. # under `serializers`, in order to minimize potential confusion with Django's
  105. # built in `ValidationError`. For example:
  106. #
  107. # from rest_framework import serializers
  108. # raise serializers.ValidationError('Value was invalid')
  109. class ValidationError(APIException):
  110. status_code = status.HTTP_400_BAD_REQUEST
  111. default_detail = _('Invalid input.')
  112. default_code = 'invalid'
  113. def __init__(self, detail=None, code=None):
  114. if detail is None:
  115. detail = self.default_detail
  116. if code is None:
  117. code = self.default_code
  118. # For validation failures, we may collect many errors together,
  119. # so the details should always be coerced to a list if not already.
  120. if not isinstance(detail, dict) and not isinstance(detail, list):
  121. detail = [detail]
  122. self.detail = _get_error_details(detail, code)
  123. class ParseError(APIException):
  124. status_code = status.HTTP_400_BAD_REQUEST
  125. default_detail = _('Malformed request.')
  126. default_code = 'parse_error'
  127. class AuthenticationFailed(APIException):
  128. status_code = status.HTTP_401_UNAUTHORIZED
  129. default_detail = _('Incorrect authentication credentials.')
  130. default_code = 'authentication_failed'
  131. class NotAuthenticated(APIException):
  132. status_code = status.HTTP_401_UNAUTHORIZED
  133. default_detail = _('Authentication credentials were not provided.')
  134. default_code = 'not_authenticated'
  135. class PermissionDenied(APIException):
  136. status_code = status.HTTP_403_FORBIDDEN
  137. default_detail = _('You do not have permission to perform this action.')
  138. default_code = 'permission_denied'
  139. class NotFound(APIException):
  140. status_code = status.HTTP_404_NOT_FOUND
  141. default_detail = _('Not found.')
  142. default_code = 'not_found'
  143. class MethodNotAllowed(APIException):
  144. status_code = status.HTTP_405_METHOD_NOT_ALLOWED
  145. default_detail = _('Method "{method}" not allowed.')
  146. default_code = 'method_not_allowed'
  147. def __init__(self, method, detail=None, code=None):
  148. if detail is None:
  149. detail = force_str(self.default_detail).format(method=method)
  150. super().__init__(detail, code)
  151. class NotAcceptable(APIException):
  152. status_code = status.HTTP_406_NOT_ACCEPTABLE
  153. default_detail = _('Could not satisfy the request Accept header.')
  154. default_code = 'not_acceptable'
  155. def __init__(self, detail=None, code=None, available_renderers=None):
  156. self.available_renderers = available_renderers
  157. super().__init__(detail, code)
  158. class UnsupportedMediaType(APIException):
  159. status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
  160. default_detail = _('Unsupported media type "{media_type}" in request.')
  161. default_code = 'unsupported_media_type'
  162. def __init__(self, media_type, detail=None, code=None):
  163. if detail is None:
  164. detail = force_str(self.default_detail).format(media_type=media_type)
  165. super().__init__(detail, code)
  166. class Throttled(APIException):
  167. status_code = status.HTTP_429_TOO_MANY_REQUESTS
  168. default_detail = _('Request was throttled.')
  169. extra_detail_singular = _('Expected available in {wait} second.')
  170. extra_detail_plural = _('Expected available in {wait} seconds.')
  171. default_code = 'throttled'
  172. def __init__(self, wait=None, detail=None, code=None):
  173. if detail is None:
  174. detail = force_str(self.default_detail)
  175. if wait is not None:
  176. wait = math.ceil(wait)
  177. detail = ' '.join((
  178. detail,
  179. force_str(ngettext(self.extra_detail_singular.format(wait=wait),
  180. self.extra_detail_plural.format(wait=wait),
  181. wait))))
  182. self.wait = wait
  183. super().__init__(detail, code)
  184. def server_error(request, *args, **kwargs):
  185. """
  186. Generic 500 error handler.
  187. """
  188. data = {
  189. 'error': 'Server Error (500)'
  190. }
  191. return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  192. def bad_request(request, exception, *args, **kwargs):
  193. """
  194. Generic 400 error handler.
  195. """
  196. data = {
  197. 'error': 'Bad Request (400)'
  198. }
  199. return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)