exceptions.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright 2013 Donald Stufft and individual contributors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # We create a clone of various builtin Exception types which additionally
  15. # inherit from CryptoError. Below, we refer to the parent types via the
  16. # `builtins` namespace, so mypy can distinguish between (e.g.)
  17. # `nacl.exceptions.RuntimeError` and `builtins.RuntimeError`.
  18. import builtins
  19. from typing import Type
  20. class CryptoError(Exception):
  21. """
  22. Base exception for all nacl related errors
  23. """
  24. class BadSignatureError(CryptoError):
  25. """
  26. Raised when the signature was forged or otherwise corrupt.
  27. """
  28. class RuntimeError(builtins.RuntimeError, CryptoError):
  29. pass
  30. class AssertionError(builtins.AssertionError, CryptoError):
  31. pass
  32. class TypeError(builtins.TypeError, CryptoError):
  33. pass
  34. class ValueError(builtins.ValueError, CryptoError):
  35. pass
  36. class InvalidkeyError(CryptoError):
  37. pass
  38. class CryptPrefixError(InvalidkeyError):
  39. pass
  40. class UnavailableError(RuntimeError):
  41. """
  42. is a subclass of :class:`~nacl.exceptions.RuntimeError`, raised when
  43. trying to call functions not available in a minimal build of
  44. libsodium.
  45. """
  46. pass
  47. def ensure(cond: bool, *args: object, **kwds: Type[Exception]) -> None:
  48. """
  49. Return if a condition is true, otherwise raise a caller-configurable
  50. :py:class:`Exception`
  51. :param bool cond: the condition to be checked
  52. :param sequence args: the arguments to be passed to the exception's
  53. constructor
  54. The only accepted named parameter is `raising` used to configure the
  55. exception to be raised if `cond` is not `True`
  56. """
  57. _CHK_UNEXP = "check_condition() got an unexpected keyword argument {0}"
  58. raising = kwds.pop("raising", AssertionError)
  59. if kwds:
  60. raise TypeError(_CHK_UNEXP.format(repr(kwds.popitem()[0])))
  61. if cond is True:
  62. return
  63. raise raising(*args)