exception_handlers.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.core.exceptions import PermissionDenied
  2. from django.core.exceptions import ValidationError as DjangoValidationError
  3. from django.http import Http404
  4. from rest_framework import exceptions
  5. from rest_framework.response import Response
  6. from rest_framework.serializers import as_serializer_error
  7. from rest_framework.views import exception_handler
  8. from account.exceptions import AccountServiceException
  9. def custom_exception_handler(exc, ctx):
  10. """
  11. {
  12. "message": "Error message",
  13. "extra": {}
  14. }
  15. """
  16. if isinstance(exc, DjangoValidationError):
  17. exc = exceptions.ValidationError(as_serializer_error(exc))
  18. if isinstance(exc, Http404):
  19. exc = exceptions.NotFound()
  20. if isinstance(exc, PermissionDenied):
  21. exc = exceptions.PermissionDenied()
  22. response = exception_handler(exc, ctx)
  23. # If unexpected error occurs (server error, etc.)
  24. if response is None:
  25. if isinstance(exc, AccountServiceException):
  26. data = {"message": exc.message, "extra": exc.extra}
  27. return Response(data, status=400)
  28. return response
  29. if isinstance(exc.detail, (list, dict)):
  30. response.data = {"detail": response.data}
  31. if isinstance(exc, exceptions.ValidationError):
  32. response.data["message"] = "Validation error"
  33. response.data["extra"] = {"fields": response.data["detail"]}
  34. else:
  35. response.data["message"] = response.data["detail"]
  36. response.data["extra"] = {}
  37. del response.data["detail"]
  38. return response