customize exception handler in Django REST Framework

Sometimes we want to customize the response in DRF. For example, we want to add some fields(such as “status”, “error message” etc.) in the data of response. As known, it’s a horrible thing that we modify every response one by one. So we need an entry point to modify the response uniformly. Fortunately, we could customize an exception handler for DRF to meet our requirement. Below is the sample code.

utils/exceptions.py
1
2
3
4
5
6
7
8
9
10
11
12
from rest_framework.views import exception_handler
from rest_framework import status

def custom_exception_handler(exc, context):
# Call django REST framework default exception handler firstly
# to get the standard error response
response = exception_handler(exc, context)

if response is not None:
# do someting you want ...

return response

But, don’t be too happy too early. There is one thing important we need to do.
We must add an item “EXCEPTION_HANDLER” in the file setting.py to tell DRF to run the customized exception handler.

settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exceptions.custom_exception_handler',
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
'PAGE_SIZE': 10
}


customize exception handler in Django REST Framework
https://r-future.github.io/post/customize-error-handler-in-DRF/
Author
Future
Posted on
July 16, 2019
Licensed under