exception_handlers.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import logging
  2. from django.db.utils import OperationalError
  3. from psl_dns.exceptions import UnsupportedRule
  4. from rest_framework import status
  5. from rest_framework.response import Response
  6. from rest_framework.views import exception_handler as drf_exception_handler
  7. def exception_handler(exc, context):
  8. """
  9. desecapi specific exception handling. If no special treatment is applied,
  10. we default to restframework's exception handling. See also
  11. https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
  12. """
  13. def _perform_handling(name):
  14. logger = logging.getLogger('django.request')
  15. logger.error('{} Supplementary Information'.format(name),
  16. exc_info=exc, stack_info=False)
  17. # Gracefully let clients know that we cannot connect to the database
  18. return Response({'detail': 'Please try again later.'},
  19. status=status.HTTP_503_SERVICE_UNAVAILABLE)
  20. # Catch DB exception and log an extra error for additional context
  21. if isinstance(exc, OperationalError):
  22. if isinstance(exc.args, (list, dict, tuple)) and exc.args and \
  23. exc.args[0] in (
  24. 2002, # Connection refused (Socket)
  25. 2003, # Connection refused (TCP)
  26. 2005, # Unresolved host name
  27. 2007, # Server protocol mismatch
  28. 2009, # Wrong host info
  29. 2026, # SSL connection error
  30. ):
  31. return _perform_handling('OperationalError')
  32. # OSError happens on system-related errors, like full disk or getaddrinfo() failure.
  33. # Catch it and log an extra error for additional context.
  34. if isinstance(exc, OSError):
  35. return _perform_handling('OSError')
  36. if isinstance(exc, UnsupportedRule):
  37. return _perform_handling('UnsupportedRule')
  38. return drf_exception_handler(exc, context)