Last active
December 15, 2018 14:35
-
-
Save aslamhadi/682e7764e240ad932223c7f89861b924 to your computer and use it in GitHub Desktop.
Custom error handler in DRF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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