1+ """
2+ This module provides functionality to format API exceptions into a structured error response.
3+
4+ It defines the `APIErrorResponse` class, which represents
5+ the structure of the error response, and the `format_exc` function, which
6+ formats exceptions into this structure according to the type of exception, its detail,
7+ and any additional settings defined in the settings.
8+
9+ Functions:
10+ - `format_exc`:
11+ Formats the given exception into a structured API error response.
12+ Used by the exception handler to return a consistent error format.
13+ """
14+
115import copy
216import logging
317from dataclasses import asdict , dataclass , field as dataclass_field
721from rest_framework import exceptions
822from rest_framework .settings import api_settings as drf_api_settings
923
24+ from drf_simple_api_errors import utils
1025from drf_simple_api_errors .settings import api_settings
1126from drf_simple_api_errors .types import APIErrorResponseDict
12- from drf_simple_api_errors .utils import camelize , flatten_dict
1327
1428logger = logging .getLogger (__name__ )
1529
@@ -46,9 +60,8 @@ def to_dict(self) -> APIErrorResponseDict:
4660 """Convert the APIErrorResponse instance to a dictionary."""
4761 response_dict = asdict (self )
4862
49- if api_settings .CAMELIZE :
50- for key in list (response_dict .keys ()):
51- response_dict [camelize (key )] = response_dict .pop (key )
63+ for key in list (response_dict .keys ()):
64+ response_dict [utils .camelize (key )] = response_dict .pop (key )
5265
5366 return response_dict
5467
@@ -112,7 +125,7 @@ def _format_exc_detail_dict(
112125 # Start by flattening the exc dict.
113126 # This is necessary as the exception detail can be nested and
114127 # we want to flatten it to a single level dict as part of this library design.
115- exc_detail = flatten_dict (copy .deepcopy (exc_detail ))
128+ exc_detail = utils . flatten_dict (copy .deepcopy (exc_detail ))
116129
117130 # Track the invalid params.
118131 # This represents the fields that are invalid and have errors associated with them.
@@ -136,7 +149,7 @@ def _format_exc_detail_dict(
136149 # N.B. If the error is a string, we will convert it to a list
137150 # to keep the consistency with the InvalidParamDict type.
138151 invalid_param = InvalidParam (
139- name = field if not api_settings . CAMELIZE else camelize (field ),
152+ name = utils . camelize (field ),
140153 reason = error if isinstance (error , list ) else [error ],
141154 )
142155 invalid_params .append (invalid_param )
0 commit comments