exceptions.py 7.9 KB

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