7

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,

2 Answers 2

11

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)
Sign up to request clarification or add additional context in comments.

2 Comments

sure, but will this provide me with a custom error via a JSON response. As Ive tried this but Im getting "global name 'Response' is not defined".
You need to import the rest_framework Response: from rest_framework.response import Response. And yes, this code will return a JSON response with the structure you specify ({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']} in this case) and the error code you need (400, check restframework status codes for more)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.