Django REST Custom Errors

I am trying to create a custom error response from a Django REST framework.

Ive included the following in my views.py ,

from rest_framework.views import exception_handler def custom_exception_handler(exc): """ Custom exception handler for Django Rest Framework that adds the `status_code` to the response and renames the `detail` key to `error`. """ response = exception_handler(exc) if response is not None: response.data['status_code'] = response.status_code response.data['error'] = response.data['detail'] response.data['detail'] = "CUSTOM ERROR" return response 

Also added the following in settings.py .

 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler' } 

Something is missing for me because I am not getting the expected response. those. custom error message in 400 API response.

Thanks,

+6
source share
2 answers

As Bibhas said, using special exception handlers you can return your own specific errors when throwing an exception. If you want to return an arbitrary response error without throwing exceptions, you need to return it in the view itself. For instance:

  return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']}, status = status.HTTP_400_BAD_REQUEST) 
+11
source

From the documentation -

Please note that the exception handler will be called only for responses generated by excluded exceptions. It will not be used for any responses returned directly by the view, such as HTTP_400_BAD_REQUEST responses returned by general views when serialization validation fails.

0
source

All Articles