In DRF, How to inject full `ErrorDetail` in the response, using a custom exception handler?

30 views Asked by At

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.

1

There are 1 answers

0
Saidi Souhaieb On

I don't know if you're using it, but you could use custom_exception_handler to transform any exceptions raised to the format you provide. Here is an example:

def custom_exception_handler(exc, context):
   response = exception_handler(exc, context)
   if response is not None:
      response.data["timestamp"] = datetime.now().isoformat()
      response.data["error_type"] = exc.__class__.__name__
      response.data["path"] = context["request"].path

   return response

Using it this is what it produced:

 {
  "detail": "Authentication credentials were not provided.",
  "timestamp": "2024-03-29T20:09:02.228370",
  "error_type": "NotAuthenticated",
  "path": "/tools/"
}

P.S.: It also can take the detail as the exception raised from validate in serializers.

Here are the docs: custom_execption_handler