I'm using a pretty complex custom handler in DRF.
For example, for a given response, response.data could look like to:
{'global_error': None, 'non_field_errors': [], 'field_errors': {'important_field': [ErrorDetail(string='Ce champ est obligatoire.', code='required')]}}
However, when getting the actual response from the API, the ErrorDetail will be transformed in a simple string, losing the code information.
Is there a simple way to ensure ErrorDetail is always written in a response as {"message": "...", "code": "..."} without transforming the response manually in the custom handler?
I know there exists the DRF get_full_details() method that returns exactly this on an exception. But I'm the response level.
I don't know if you're using it, but you could use
custom_exception_handlerto transform any exceptions raised to the format you provide. Here is an example:Using it this is what it produced:
P.S.: It also can take the detail as the exception raised from
validatein serializers.Here are the docs: custom_execption_handler