I'm new to django rest_framework, And tried to create customized error reponse in django!.
Django Rest Framework Exceptions
After going through that, all seems to be pretty straight forward, but the import error raise when i try to add the custom exception.
Settings.py
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'
}
ImportError Exception Value:
Could not import 'project.restapi.utils.custom_exception_handler' for API setting 'EXCEPTION_HANDLER'. AttributeError: module 'project.restapi.utils' has no attribute 'custom_exception_handler'
custom_exception_handler.py
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code
    return response
model.py
class Users(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    def retrieve(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(Users, self).retrieve(request, *args, **kwargs) 
        response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0"}
        # customize the response data
        if response is not None:
            return response
        else:
            # return response with this custom representation
            response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0","error":response.exception}
            return response
So on the above model works fine, except when i try to hit the user which is not in the database should raise error - not found, so i tried to customise the not found to be meaningful to my own. that's it
I tried to sort out, but hard to do so!!,
Django Version: 2.1.5 Python - 3.7.0
Since your custom_exception_handler resides in a file named custom_exception_handler.py. You can try changing the EXCEPTION_HANDLER setting to this:
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler.custom_exception_handler'
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With