felix001
felix001

Reputation: 16691

Django REST Custom Errors

I’m trying to create a custom error response from the REST Django framework.

I’ve 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

And also added the following to settings.py.

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

Am I missing something as I don’t get the expected response. i.e a custom error message in the 400 API response.

Thanks,

Upvotes: 7

Views: 5566

Answers (2)

argaen
argaen

Reputation: 4245

As Bibhas said, with custom exception handlers, you only can return own defined errors when an exception is called. If you want to return a custom response error without exceptions being triggered, you need to return it in the view itself. For example:

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

Upvotes: 11

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

From the documentation -

Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

Upvotes: 0

Related Questions