exception.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """Common DNS Exceptions.
  17. Dnspython modules may also define their own exceptions, which will
  18. always be subclasses of ``DNSException``.
  19. """
  20. from typing import Optional, Set
  21. class DNSException(Exception):
  22. """Abstract base class shared by all dnspython exceptions.
  23. It supports two basic modes of operation:
  24. a) Old/compatible mode is used if ``__init__`` was called with
  25. empty *kwargs*. In compatible mode all *args* are passed
  26. to the standard Python Exception class as before and all *args* are
  27. printed by the standard ``__str__`` implementation. Class variable
  28. ``msg`` (or doc string if ``msg`` is ``None``) is returned from ``str()``
  29. if *args* is empty.
  30. b) New/parametrized mode is used if ``__init__`` was called with
  31. non-empty *kwargs*.
  32. In the new mode *args* must be empty and all kwargs must match
  33. those set in class variable ``supp_kwargs``. All kwargs are stored inside
  34. ``self.kwargs`` and used in a new ``__str__`` implementation to construct
  35. a formatted message based on the ``fmt`` class variable, a ``string``.
  36. In the simplest case it is enough to override the ``supp_kwargs``
  37. and ``fmt`` class variables to get nice parametrized messages.
  38. """
  39. msg: Optional[str] = None # non-parametrized message
  40. supp_kwargs: Set[str] = set() # accepted parameters for _fmt_kwargs (sanity check)
  41. fmt: Optional[str] = None # message parametrized with results from _fmt_kwargs
  42. def __init__(self, *args, **kwargs):
  43. self._check_params(*args, **kwargs)
  44. if kwargs:
  45. # This call to a virtual method from __init__ is ok in our usage
  46. self.kwargs = self._check_kwargs(**kwargs) # lgtm[py/init-calls-subclass]
  47. self.msg = str(self)
  48. else:
  49. self.kwargs = dict() # defined but empty for old mode exceptions
  50. if self.msg is None:
  51. # doc string is better implicit message than empty string
  52. self.msg = self.__doc__
  53. if args:
  54. super().__init__(*args)
  55. else:
  56. super().__init__(self.msg)
  57. def _check_params(self, *args, **kwargs):
  58. """Old exceptions supported only args and not kwargs.
  59. For sanity we do not allow to mix old and new behavior."""
  60. if args or kwargs:
  61. assert bool(args) != bool(
  62. kwargs
  63. ), "keyword arguments are mutually exclusive with positional args"
  64. def _check_kwargs(self, **kwargs):
  65. if kwargs:
  66. assert (
  67. set(kwargs.keys()) == self.supp_kwargs
  68. ), f"following set of keyword args is required: {self.supp_kwargs}"
  69. return kwargs
  70. def _fmt_kwargs(self, **kwargs):
  71. """Format kwargs before printing them.
  72. Resulting dictionary has to have keys necessary for str.format call
  73. on fmt class variable.
  74. """
  75. fmtargs = {}
  76. for kw, data in kwargs.items():
  77. if isinstance(data, (list, set)):
  78. # convert list of <someobj> to list of str(<someobj>)
  79. fmtargs[kw] = list(map(str, data))
  80. if len(fmtargs[kw]) == 1:
  81. # remove list brackets [] from single-item lists
  82. fmtargs[kw] = fmtargs[kw].pop()
  83. else:
  84. fmtargs[kw] = data
  85. return fmtargs
  86. def __str__(self):
  87. if self.kwargs and self.fmt:
  88. # provide custom message constructed from keyword arguments
  89. fmtargs = self._fmt_kwargs(**self.kwargs)
  90. return self.fmt.format(**fmtargs)
  91. else:
  92. # print *args directly in the same way as old DNSException
  93. return super().__str__()
  94. class FormError(DNSException):
  95. """DNS message is malformed."""
  96. class SyntaxError(DNSException):
  97. """Text input is malformed."""
  98. class UnexpectedEnd(SyntaxError):
  99. """Text input ended unexpectedly."""
  100. class TooBig(DNSException):
  101. """The DNS message is too big."""
  102. class Timeout(DNSException):
  103. """The DNS operation timed out."""
  104. supp_kwargs = {"timeout"}
  105. fmt = "The DNS operation timed out after {timeout:.3f} seconds"
  106. # We do this as otherwise mypy complains about unexpected keyword argument
  107. # idna_exception
  108. def __init__(self, *args, **kwargs):
  109. super().__init__(*args, **kwargs)
  110. class UnsupportedAlgorithm(DNSException):
  111. """The DNSSEC algorithm is not supported."""
  112. class AlgorithmKeyMismatch(UnsupportedAlgorithm):
  113. """The DNSSEC algorithm is not supported for the given key type."""
  114. class ValidationFailure(DNSException):
  115. """The DNSSEC signature is invalid."""
  116. class DeniedByPolicy(DNSException):
  117. """Denied by DNSSEC policy."""
  118. class ExceptionWrapper:
  119. def __init__(self, exception_class):
  120. self.exception_class = exception_class
  121. def __enter__(self):
  122. return self
  123. def __exit__(self, exc_type, exc_val, exc_tb):
  124. if exc_type is not None and not isinstance(exc_val, self.exception_class):
  125. raise self.exception_class(str(exc_val)) from exc_val
  126. return False