1"""Exception classes for marshmallow-related errors.""" 2import typing 3 4 5# Key used for schema-level validation errors 6SCHEMA = "_schema" 7 8 9class MarshmallowError(Exception): 10 """Base class for all marshmallow-related errors.""" 11 12 13class ValidationError(MarshmallowError): 14 """Raised when validation fails on a field or schema. 15 16 Validators and custom fields should raise this exception. 17 18 :param message: An error message, list of error messages, or dict of 19 error messages. If a dict, the keys are subitems and the values are error messages. 20 :param field_name: Field name to store the error on. 21 If `None`, the error is stored as schema-level error. 22 :param data: Raw input data. 23 :param valid_data: Valid (de)serialized data. 24 """ 25 26 def __init__( 27 self, 28 message: typing.Union[str, typing.List, typing.Dict], 29 field_name: str = SCHEMA, 30 data: typing.Optional[ 31 typing.Union[ 32 typing.Mapping[str, typing.Any], 33 typing.Iterable[typing.Mapping[str, typing.Any]], 34 ] 35 ] = None, 36 valid_data: typing.Optional[ 37 typing.Union[ 38 typing.List[typing.Dict[str, typing.Any]], 39 typing.Dict[str, typing.Any], 40 ] 41 ] = None, 42 **kwargs, 43 ): 44 self.messages = [message] if isinstance(message, (str, bytes)) else message 45 self.field_name = field_name 46 self.data = data 47 self.valid_data = valid_data 48 self.kwargs = kwargs 49 super().__init__(message) 50 51 def normalized_messages(self): 52 if self.field_name == SCHEMA and isinstance(self.messages, dict): 53 return self.messages 54 return {self.field_name: self.messages} 55 56 57class RegistryError(NameError): 58 """Raised when an invalid operation is performed on the serializer 59 class registry. 60 """ 61 62 63class StringNotCollectionError(MarshmallowError, TypeError): 64 """Raised when a string is passed when a list of strings is expected.""" 65 66 67class FieldInstanceResolutionError(MarshmallowError, TypeError): 68 """Raised when schema to instantiate is neither a Schema class nor an instance.""" 69