While using DRF, do you need to handle the exceptions yourselves? Here’s how to do it. First, we need to create an exception handler function like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from rest_framework.views import exception_handler def custom_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: data = response.data response.data = {} errors = [] for field, value in data.items(): errors.append("{} : {}".format(field, " ".join(value))) response.data['errors'] = errors response.data['status'] = False response.data['exception'] = str(exc) return response |
In the exception handler, we get exc
which is the exception raised and the context
contains the context of the request. However, we didn’t do anything fancy with these. We just called the default exception handler and joined the errors in a flat string. We also added the exception to our response.
Now, we need to tell DRF to call our custom exception handler when it comes across an exception. That is easy:
Open up your settings.py
and look for the REST_FRAMEWORK
dictionary. Here you need to add the exception handler to the EXCEPTION_HANDLER
key. So it should look something like this:
1 2 3 4 5 6 7 8 9 10 |
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'EXCEPTION_HANDLER': 'api.utils.custom_exception_handler' } |