exception_handlers.py 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. from django.db.utils import OperationalError
  2. from rest_framework import status
  3. from rest_framework.response import Response
  4. from rest_framework.views import exception_handler
  5. import logging
  6. def handle_db_unavailable(exc, context):
  7. """
  8. desecapi specific exception handling. If no special treatment is applied,
  9. we default to restframework's exception handling. See also
  10. https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
  11. """
  12. if isinstance(exc, OperationalError):
  13. if isinstance(exc.args, (list, dict, tuple)) and exc.args and \
  14. exc.args[0] in (
  15. 2002, # Connection refused (Socket)
  16. 2003, # Connection refused (TCP)
  17. 2005, # Unresolved host name
  18. 2007, # Server protocol mismatch
  19. 2009, # Wrong host info
  20. 2026, # SSL connection error
  21. ):
  22. logging.getLogger('django.request').error('OperationalError Supplementary Information',
  23. exc_info=exc, stack_info=False)
  24. # Gracefully let clients know that we cannot connect to the database
  25. data = {'detail': 'Please try again later.'}
  26. return Response(data, status=status.HTTP_503_SERVICE_UNAVAILABLE)
  27. return exception_handler(exc, context)