Skip to content

Instantly share code, notes, and snippets.

@Behoston
Created November 3, 2022 12:08
Show Gist options
  • Save Behoston/debc6b0db8d0bcddc23976c6f059ccf8 to your computer and use it in GitHub Desktop.
Save Behoston/debc6b0db8d0bcddc23976c6f059ccf8 to your computer and use it in GitHub Desktop.
import collections
import typing
from django.conf import settings
from django.db.models import ProtectedError
from django.db.models import RestrictedError
from rest_framework.response import Response
from rest_framework.views import exception_handler
from rollbar.contrib.django_rest_framework import post_exception_handler
def dostanesie_exception_handler(exc, context):
if settings.DEBUG:
super_result = exception_handler(exc, context)
else:
super_result = post_exception_handler(exc, context)
if super_result is not None:
return super_result
if isinstance(exc, (RestrictedError, ProtectedError)):
objects = getattr(exc, 'restricted_objects', None) or getattr(exc, 'protected_objects', None)
return Response(status=423, data={
'detail': 'Some objects dependent on this resource are protected or restricted',
'objects': _parse_objects(objects),
})
def _parse_objects(objects: set) -> typing.Dict[str, int]:
return {k.__name__: v for k, v in collections.Counter(map(type, objects)).items()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment