Django Rest Framework Customize Exception Handler Response

django rest framework

Introduction

Django Rest Framework a.k.a. DRF is now the de facto tool for designing REST APIs using Django. It is a highly customizable framework and comes with cool features like Web Browsable API. In this quick tutorial, we will see how to customize default exception handling policies of DRF.

Need of Custom Exception Handler

By default, DRF gives response in below format,

HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 42

{"detail": "Method 'DELETE' not allowed."}

But many times, we use different JSON schemas. So you may want to customize above default output response of handler.

How to add custom Exception Handler

The easiest way to do this is, add your own exception handler and hook it up with DRF. Lets add a new file in your Django app called exceptions.py (You can use any name). Add below content in it.

from rest_framework.views import exception_handler

def my_exception_handler(exc, context):    
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    return response

Now add path of this handler in your settings.py with other settings of DRF as below.

REST_FRAMEWORK = {
    .
    .
    .
    'EXCEPTION_HANDLER': 'my_project.my_app.exceptions.my_exception_handler'
}

That’s all. We are ready to rumble.

How to customize output response

By default, when there is no exception, the response is None. So we can add our custom response if only an exception occurs. See below example.

from rest_framework.views import exception_handler

def my_exception_handler(exc, context):    
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    if response is not None:
        response.data["message"] = str(exc)
        response.data["results"] = None
        del response.data["detail"]
    return response

Isn’t this easy ? Hope this helps you. See you again !

Leave a Reply