Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework : How to initialise & use custom exception handler?

DRF newbie here.

I'm trying to handle all exceptions within the project through a custom exception handler. Basically, what I'm trying to do is if any serializer fails to validate the data, I want to send the corresponding error messages to my custom exception handler and reformat errors accordingly.

I've added the following to settings.py.

# DECLARATIONS FOR REST FRAMEWORK
REST_FRAMEWORK = {
    'PAGE_SIZE': 20,
    'EXCEPTION_HANDLER': 'main.exceptions.base_exception_handler',

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    )
}

But once I send an invalid parameter to any of the endpoints in the project, I still get a default error message of the DRF validator. (e.g. {u'email': [u'This field is required.']})

Errors raised on corresponding serializer's validate function, never reaches to my exception handler.

Here is an image of the Project Tree that I'm working on.

Am I missing something?

Thank you in advance.

like image 208
hnroot Avatar asked May 12 '16 13:05

hnroot


1 Answers

To do that, your base_exception_handler should check when a ValidationError exception is being raised and then modify and return the custom error response.

(Note: A serializer raises ValidationError exception if the data parameters are invalid and then 400 status is returned.)

In base_exception_handler, we will check if the exception being raised is of the type ValidationError and then modify the errors format and return that modified errors response.

from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError

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

    # check that a ValidationError exception is raised
    if isinstance(exc, ValidationError): 
        # here prepare the 'custom_error_response' and
        # set the custom response data on response object
        response.data = custom_error_response 

    return response
like image 83
Rahul Gupta Avatar answered Nov 03 '22 11:11

Rahul Gupta