exception_handlers.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import logging
  2. from django.db.utils import IntegrityError, OperationalError
  3. from rest_framework import status
  4. from rest_framework.response import Response
  5. from rest_framework.views import exception_handler as drf_exception_handler
  6. from desecapi import metrics
  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 _log():
  15. logger = logging.getLogger('django.request')
  16. logger.error('{} Supplementary Information'.format(exc.__class__),
  17. exc_info=exc, stack_info=False)
  18. def _409():
  19. return Response({'detail': f'Conflict: {exc}'}, status=status.HTTP_409_CONFLICT)
  20. def _500():
  21. return Response({'detail': "Internal Server Error. We're on it!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  22. def _503():
  23. return Response({'detail': 'Please try again later.'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
  24. # Catch DB OperationalError and log an extra error for additional context
  25. if (
  26. isinstance(exc, OperationalError) and
  27. isinstance(exc.args, (list, dict, tuple)) and
  28. exc.args and
  29. exc.args[0] in (
  30. 2002, # Connection refused (Socket)
  31. 2003, # Connection refused (TCP)
  32. 2005, # Unresolved host name
  33. 2007, # Server protocol mismatch
  34. 2009, # Wrong host info
  35. 2026, # SSL connection error
  36. )
  37. ):
  38. _log()
  39. metrics.get('desecapi_database_unavailable').inc()
  40. return _503()
  41. handlers = {
  42. IntegrityError: _409,
  43. OSError: _500, # OSError happens on system-related errors, like full disk or getaddrinfo() failure.
  44. PDNSException: _500, # nslord/nsmaster returned an error
  45. }
  46. for exception_class, handler in handlers.items():
  47. if isinstance(exc, exception_class):
  48. _log()
  49. # TODO add metrics
  50. return handler()
  51. return drf_exception_handler(exc, context)