exceptions.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. """Exception classes for marshmallow-related errors."""
  3. from marshmallow.compat import basestring
  4. # Key used for schema-level validation errors
  5. SCHEMA = '_schema'
  6. class MarshmallowError(Exception):
  7. """Base class for all marshmallow-related errors."""
  8. class ValidationError(MarshmallowError):
  9. """Raised when validation fails on a field or schema.
  10. Validators and custom fields should raise this exception.
  11. :param str|list|dict message: An error message, list of error messages, or dict of
  12. error messages. If a dict, the keys are subitems and the values are error messages.
  13. :param str field_name: Field name to store the error on.
  14. If `None`, the error is stored as schema-level error.
  15. :param dict data: Raw input data.
  16. :param dict valid_data: Valid (de)serialized data.
  17. """
  18. def __init__(self, message, field_name=SCHEMA, data=None, valid_data=None, **kwargs):
  19. self.messages = [message] if isinstance(message, basestring) else message
  20. self.field_name = field_name
  21. self.data = data
  22. self.valid_data = valid_data
  23. self.kwargs = kwargs
  24. MarshmallowError.__init__(self, message)
  25. def normalized_messages(self):
  26. if self.field_name == SCHEMA and isinstance(self.messages, dict):
  27. return self.messages
  28. return {self.field_name: self.messages}
  29. class RegistryError(NameError):
  30. """Raised when an invalid operation is performed on the serializer
  31. class registry.
  32. """
  33. class StringNotCollectionError(MarshmallowError, TypeError):
  34. """Raised when a string is passed when a list of strings is expected."""
  35. class FieldInstanceResolutionError(MarshmallowError, TypeError):
  36. """Raised when schema to instantiate is neither a Schema class nor an instance."""