exceptions.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import six
  4. from library.validator.utils import force_text, force_str
  5. from library.validator.translation import gettext as _
  6. def _flat_error_detail(detail):
  7. if isinstance(detail, list):
  8. return [_flat_error_detail(item) for item in detail]
  9. elif isinstance(detail, dict):
  10. return {
  11. key: _flat_error_detail(value)
  12. for key, value in six.iteritems(detail)
  13. }
  14. else:
  15. return force_text(detail)
  16. class BaseValidationError(Exception):
  17. default_detail = _('Base validation error')
  18. default_code = _('error')
  19. def __init__(self, detail=None, code=None):
  20. """
  21. :param detail: `detail` maybe a string, a dict or a list.
  22. :param code: error code, it not used for now.
  23. """
  24. if detail is None:
  25. detail = self.default_detail
  26. if code is None:
  27. code = self.default_code
  28. self.detail = _flat_error_detail(detail)
  29. self.code = code
  30. def get_detail(self):
  31. return self.detail
  32. def __str__(self):
  33. return force_str(self.detail)
  34. def __unicode__(self):
  35. return force_text(self.detail)
  36. def __repr__(self):
  37. detail = self.detail
  38. if len(detail) > 103:
  39. detail = detail[:100] + '...'
  40. return '{0}(detail={1!r})'.format(self.__class__.__name__, detail)
  41. class FieldRequiredError(BaseValidationError):
  42. default_detail = _('Field is required')
  43. default_code = _('error')
  44. class ValidationError(BaseValidationError):
  45. default_detail = _('Validation error')
  46. default_code = _('error')
  47. class FieldValidationError(BaseValidationError):
  48. default_detail = _('field Validation error')
  49. default_code = _('error')
  50. class UnicodeValidationError(FieldValidationError):
  51. def __init__(self, detail, code="error"):
  52. self.detail = detail
  53. self.code = code
  54. def __str__(self):
  55. return self.detail
  56. def __unicode__(self):
  57. return self.__str__()