Coerce validation exceptions into a standardized serialized error format. This function normalizes both Django's `ValidationError` and REST framework's `ValidationError` into a dictionary structure compatible with serializer `.errors`, ensuring all values are represented as lis
(exc)
| 312 | |
| 313 | |
| 314 | def as_serializer_error(exc): |
| 315 | """ |
| 316 | Coerce validation exceptions into a standardized serialized error format. |
| 317 | |
| 318 | This function normalizes both Django's `ValidationError` and REST |
| 319 | framework's `ValidationError` into a dictionary structure compatible |
| 320 | with serializer `.errors`, ensuring all values are represented as |
| 321 | lists of error details. |
| 322 | |
| 323 | The returned structure conforms to the serializer error contract: |
| 324 | - Field-specific errors are returned as '{field-name: [errors]}' |
| 325 | - Non-field errors are returned under the 'NON_FIELD_ERRORS_KEY' |
| 326 | """ |
| 327 | assert isinstance(exc, (ValidationError, DjangoValidationError)) |
| 328 | |
| 329 | if isinstance(exc, DjangoValidationError): |
| 330 | detail = get_error_detail(exc) |
| 331 | else: |
| 332 | detail = exc.detail |
| 333 | |
| 334 | if isinstance(detail, Mapping): |
| 335 | # If errors may be a dict we use the standard {key: list of values}. |
| 336 | # Here we ensure that all the values are *lists* of errors. |
| 337 | return { |
| 338 | key: value if isinstance(value, (list, Mapping)) else [value] |
| 339 | for key, value in detail.items() |
| 340 | } |
| 341 | elif isinstance(detail, list): |
| 342 | # Errors raised as a list are non-field errors. |
| 343 | return { |
| 344 | api_settings.NON_FIELD_ERRORS_KEY: detail |
| 345 | } |
| 346 | # Errors raised as a string are non-field errors. |
| 347 | return { |
| 348 | api_settings.NON_FIELD_ERRORS_KEY: [detail] |
| 349 | } |
| 350 | |
| 351 | |
| 352 | class Serializer(BaseSerializer, metaclass=SerializerMetaclass): |
no test coverage detected