8

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.

0

1 Answer 1

6

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

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.