exception_handlers.py 1.2 KB

1234567891011121314151617181920212223242526272829
  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, set_rollback
  5. def handle_db_unavailable(exc, context):
  6. """
  7. desecapi specific exception handling. If no special treatment is applied,
  8. we default to restframework's exception handling. See also
  9. https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
  10. """
  11. if isinstance(exc, OperationalError):
  12. if isinstance(exc.args, (list, dict, tuple)) and exc.args and \
  13. exc.args[0] in (
  14. 2002, # Connection refused (Socket)
  15. 2003, # Connection refused (TCP)
  16. 2005, # Unresolved host name
  17. 2007, # Server protocol mismatch
  18. 2009, # Wrong host info
  19. 2026, # SSL connection error
  20. ):
  21. # Gracefully let clients know that we cannot connect to the database
  22. data = {'detail': 'Please try again later.'}
  23. return Response(data, status=status.HTTP_503_SERVICE_UNAVAILABLE)
  24. return exception_handler(exc, context)