exceptions.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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, tuple)):
  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. result = super().__eq__(other)
  62. if result is NotImplemented:
  63. return NotImplemented
  64. try:
  65. return result and self.code == other.code
  66. except AttributeError:
  67. return result
  68. def __ne__(self, other):
  69. result = self.__eq__(other)
  70. if result is NotImplemented:
  71. return NotImplemented
  72. return not result
  73. def __repr__(self):
  74. return 'ErrorDetail(string=%r, code=%r)' % (
  75. str(self),
  76. self.code,
  77. )
  78. def __hash__(self):
  79. return hash(str(self))
  80. class APIException(Exception):
  81. """
  82. Base class for REST framework exceptions.
  83. Subclasses should provide `.status_code` and `.default_detail` properties.
  84. """
  85. status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
  86. default_detail = _('A server error occurred.')
  87. default_code = 'error'
  88. def __init__(self, detail=None, code=None):
  89. if detail is None:
  90. detail = self.default_detail
  91. if code is None:
  92. code = self.default_code
  93. self.detail = _get_error_details(detail, code)
  94. def __str__(self):
  95. return str(self.detail)
  96. def get_codes(self):
  97. """
  98. Return only the code part of the error details.
  99. Eg. {"name": ["required"]}
  100. """
  101. return _get_codes(self.detail)
  102. def get_full_details(self):
  103. """
  104. Return both the message & code parts of the error details.
  105. Eg. {"name": [{"message": "This field is required.", "code": "required"}]}
  106. """
  107. return _get_full_details(self.detail)
  108. # The recommended style for using `ValidationError` is to keep it namespaced
  109. # under `serializers`, in order to minimize potential confusion with Django's
  110. # built in `ValidationError`. For example:
  111. #
  112. # from rest_framework import serializers
  113. # raise serializers.ValidationError('Value was invalid')
  114. class ValidationError(APIException):
  115. status_code = status.HTTP_400_BAD_REQUEST
  116. default_detail = _('Invalid input.')
  117. default_code = 'invalid'
  118. def __init__(self, detail=None, code=None):
  119. if detail is None:
  120. detail = self.default_detail
  121. if code is None:
  122. code = self.default_code
  123. # For validation failures, we may collect many errors together,
  124. # so the details should always be coerced to a list if not already.
  125. if isinstance(detail, tuple):
  126. detail = list(detail)
  127. elif not isinstance(detail, dict) and not isinstance(detail, list):
  128. detail = [detail]
  129. self.detail = _get_error_details(detail, code)
  130. class ParseError(APIException):
  131. status_code = status.HTTP_400_BAD_REQUEST
  132. default_detail = _('Malformed request.')
  133. default_code = 'parse_error'
  134. class AuthenticationFailed(APIException):
  135. status_code = status.HTTP_401_UNAUTHORIZED
  136. default_detail = _('Incorrect authentication credentials.')
  137. default_code = 'authentication_failed'
  138. class NotAuthenticated(APIException):
  139. status_code = status.HTTP_401_UNAUTHORIZED
  140. default_detail = _('Authentication credentials were not provided.')
  141. default_code = 'not_authenticated'
  142. class PermissionDenied(APIException):
  143. status_code = status.HTTP_403_FORBIDDEN
  144. default_detail = _('You do not have permission to perform this action.')
  145. default_code = 'permission_denied'
  146. class NotFound(APIException):
  147. status_code = status.HTTP_404_NOT_FOUND
  148. default_detail = _('Not found.')
  149. default_code = 'not_found'
  150. class MethodNotAllowed(APIException):
  151. status_code = status.HTTP_405_METHOD_NOT_ALLOWED
  152. default_detail = _('Method "{method}" not allowed.')
  153. default_code = 'method_not_allowed'
  154. def __init__(self, method, detail=None, code=None):
  155. if detail is None:
  156. detail = force_str(self.default_detail).format(method=method)
  157. super().__init__(detail, code)
  158. class NotAcceptable(APIException):
  159. status_code = status.HTTP_406_NOT_ACCEPTABLE
  160. default_detail = _('Could not satisfy the request Accept header.')
  161. default_code = 'not_acceptable'
  162. def __init__(self, detail=None, code=None, available_renderers=None):
  163. self.available_renderers = available_renderers
  164. super().__init__(detail, code)
  165. class UnsupportedMediaType(APIException):
  166. status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
  167. default_detail = _('Unsupported media type "{media_type}" in request.')
  168. default_code = 'unsupported_media_type'
  169. def __init__(self, media_type, detail=None, code=None):
  170. if detail is None:
  171. detail = force_str(self.default_detail).format(media_type=media_type)
  172. super().__init__(detail, code)
  173. class Throttled(APIException):
  174. status_code = status.HTTP_429_TOO_MANY_REQUESTS
  175. default_detail = _('Request was throttled.')
  176. extra_detail_singular = _('Expected available in {wait} second.')
  177. extra_detail_plural = _('Expected available in {wait} seconds.')
  178. default_code = 'throttled'
  179. def __init__(self, wait=None, detail=None, code=None):
  180. if detail is None:
  181. detail = force_str(self.default_detail)
  182. if wait is not None:
  183. wait = math.ceil(wait)
  184. detail = ' '.join((
  185. detail,
  186. force_str(ngettext(self.extra_detail_singular.format(wait=wait),
  187. self.extra_detail_plural.format(wait=wait),
  188. wait))))
  189. self.wait = wait
  190. super().__init__(detail, code)
  191. def server_error(request, *args, **kwargs):
  192. """
  193. Generic 500 error handler.
  194. """
  195. data = {
  196. 'error': 'Server Error (500)'
  197. }
  198. return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  199. def bad_request(request, exception, *args, **kwargs):
  200. """
  201. Generic 400 error handler.
  202. """
  203. data = {
  204. 'error': 'Bad Request (400)'
  205. }
  206. return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)