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' } |
7 replies on “Django REST Framework: Custom Exception Handler”
Hi Masnun,
Where to put exception handlers? It is on separate python file?
add utails.py in your api app
Hi,
There is an error in your code on the 10 line. If you set response.data to {} then cycle on the line 12 would not populate errors, because response.data is {} so you should copy response.data before point it to empty dictionary
Hello Masnun Vai,
you initialize first
response.data = {}
but again iter response response.data.items()
it looks wrong !!
It is wrong. I didn’t notice the first part.
Why you are iterating over response.data, since it has been declared as empty dict.
My bad. Thanks for pointing out.