exception_handlers.py 2.0 KB

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