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 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 Comments Django REST Framework: Custom Exception Handler

  1. Vovk


    There is an error in your code on the 10 line. If you set to {} then cycle on the line 12 would not populate errors, because is {} so you should copy before point it to empty dictionary

  2. Asif

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


Leave a Reply

Your email address will not be published. Required fields are marked *