Validation exception. May represent an error validating a field or a document containing fields with validation errors. :ivar errors: A dictionary of errors for fields within this document or list, or None if the error is for an individual field.
| 73 | |
| 74 | |
| 75 | class ValidationError(AssertionError): |
| 76 | """Validation exception. |
| 77 | |
| 78 | May represent an error validating a field or a |
| 79 | document containing fields with validation errors. |
| 80 | |
| 81 | :ivar errors: A dictionary of errors for fields within this |
| 82 | document or list, or None if the error is for an |
| 83 | individual field. |
| 84 | """ |
| 85 | |
| 86 | errors = {} |
| 87 | field_name = None |
| 88 | _message = None |
| 89 | |
| 90 | def __init__(self, message="", **kwargs): |
| 91 | super().__init__(message) |
| 92 | self.errors = kwargs.get("errors", {}) |
| 93 | self.field_name = kwargs.get("field_name") |
| 94 | self.message = message |
| 95 | |
| 96 | def __str__(self): |
| 97 | return str(self.message) |
| 98 | |
| 99 | def __repr__(self): |
| 100 | return f"{self.__class__.__name__}({self.message},)" |
| 101 | |
| 102 | def __getattribute__(self, name): |
| 103 | message = super().__getattribute__(name) |
| 104 | if name == "message": |
| 105 | if self.field_name: |
| 106 | message = "%s" % message |
| 107 | if self.errors: |
| 108 | message = f"{message}({self._format_errors()})" |
| 109 | return message |
| 110 | |
| 111 | def _get_message(self): |
| 112 | return self._message |
| 113 | |
| 114 | def _set_message(self, message): |
| 115 | self._message = message |
| 116 | |
| 117 | message = property(_get_message, _set_message) |
| 118 | |
| 119 | def to_dict(self): |
| 120 | """Returns a dictionary of all errors within a document |
| 121 | |
| 122 | Keys are field names or list indices and values are the |
| 123 | validation error messages, or a nested dictionary of |
| 124 | errors for an embedded document or list. |
| 125 | """ |
| 126 | |
| 127 | def build_dict(source): |
| 128 | errors_dict = {} |
| 129 | if isinstance(source, dict): |
| 130 | for field_name, error in source.items(): |
| 131 | errors_dict[field_name] = build_dict(error) |
| 132 | elif isinstance(source, ValidationError) and source.errors: |
no outgoing calls