MCPcopy
hub / github.com/encode/django-rest-framework / as_serializer_error

Function as_serializer_error

rest_framework/serializers.py:314–349  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

312
313
314def 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
352class Serializer(BaseSerializer, metaclass=SerializerMetaclass):

Callers 2

run_validationMethod · 0.85
run_validationMethod · 0.85

Calls 1

get_error_detailFunction · 0.90

Tested by

no test coverage detected