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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With