Categories
Django Python

Django REST Framework: Custom Exception Handler

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:

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:

7 replies on “Django REST Framework: Custom Exception Handler”

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

Why you are iterating over response.data, since it has been declared as empty dict.

Comments are closed.