Skip to content

Instantly share code, notes, and snippets.

@a4amaan
Created October 25, 2020 17:52
Show Gist options
  • Save a4amaan/ce79f7724bcc65bfa8ba88efc38efe13 to your computer and use it in GitHub Desktop.
Save a4amaan/ce79f7724bcc65bfa8ba88efc38efe13 to your computer and use it in GitHub Desktop.
DRF Global Exception Handler
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.exceptions import AuthenticationFailed as DRFAuthenticationFailed
from rest_framework.views import exception_handler as drf_exception_handler
def exception_handler(exc, context):
"""Handle Django ValidationError as an accepted exception
https://stackoverflow.com/questions/48757816/catch-all-exceptions-in-django-rest-framework
Must be set in settings:
>>> REST_FRAMEWORK = {
... # ...
... 'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
... # ...
... }
For the parameters, see ``exception_handler``
"""
# print("Exception Instance", type(exc))
if isinstance(exc, DjangoValidationError):
if hasattr(exc, 'message_dict'):
exc = DRFValidationError(detail={'error': exc.message_dict})
elif hasattr(exc, 'message'):
exc = DRFValidationError(detail={'error': exc.message})
elif hasattr(exc, 'messages'):
exc = DRFValidationError(detail={'error': exc.messages})
if isinstance(exc, User.DoesNotExist):
exc = DRFAuthenticationFailed(detail={'error': "Access token expired or invalid user token used"})
if isinstance(exc, ValueError):
if hasattr(exc, 'message_dict'):
exc = DRFValidationError(detail={'error': exc.message_dict})
elif hasattr(exc, 'message'):
exc = DRFValidationError(detail={'error': exc.message})
elif hasattr(exc, 'messages'):
exc = DRFValidationError(detail={'error': exc.messages})
return drf_exception_handler(exc, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment