Skip to content

Instantly share code, notes, and snippets.

@aslamhadi
Last active December 15, 2018 14:35
Show Gist options
  • Save aslamhadi/682e7764e240ad932223c7f89861b924 to your computer and use it in GitHub Desktop.
Save aslamhadi/682e7764e240ad932223c7f89861b924 to your computer and use it in GitHub Desktop.
Custom error handler in DRF
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:
# check if exception has dict items
if hasattr(exc.detail, 'items'):
# remove the initial value
response.data = {}
errors = []
for key, value in exc.detail.items():
# append errors into the list
errors.append("{} : {}".format(key, " ".join(value)))
# add property errors to the response
response.data['errors'] = errors
# serve status code in the response
response.data['status_code'] = response.status_code
return response
@esfandiaryfard
Copy link

I did this in my project but when I try to define my settings it raises an error that No module named my_project.my_app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment