Debian Codegraph @

src/nacl/exceptions.py

raw
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
15
16 # We create a clone of various builtin Exception types which additionally
17 # inherit from CryptoError. Below, we refer to the parent types via the
18 # `builtins` namespace, so mypy can distinguish between (e.g.)
19 # `nacl.exceptions.RuntimeError` and `builtins.RuntimeError`.
20 import builtins
21 from typing import Type
22
23
24 class CryptoError(Exception):
25 """
26 Base exception for all nacl related errors
27 """
28
29
30 class BadSignatureError(CryptoError):
31 """
32 Raised when the signature was forged or otherwise corrupt.
33 """
34
35
36 class RuntimeError(builtins.RuntimeError, CryptoError):
37 pass
38
39
40 class AssertionError(builtins.AssertionError, CryptoError):
41 pass
42
43
44 class TypeError(builtins.TypeError, CryptoError):
45 pass
46
47
48 class ValueError(builtins.ValueError, CryptoError):
49 pass
50
51
52 class InvalidkeyError(CryptoError):
53 pass
54
55
56 class CryptPrefixError(InvalidkeyError):
57 pass
58
59
60 class UnavailableError(RuntimeError):
61 """
62 is a subclass of :class:`~nacl.exceptions.RuntimeError`, raised when
63 trying to call functions not available in a minimal build of
64 libsodium or due to hardware limitations.
65 """
66
67 pass
68
69
70 def ensure(cond: bool, *args: object, **kwds: Type[Exception]) -> None:
71 """
72 Return if a condition is true, otherwise raise a caller-configurable
73 :py:class:`Exception`
74 :param bool cond: the condition to be checked
75 :param sequence args: the arguments to be passed to the exception's
76 constructor
77 The only accepted named parameter is `raising` used to configure the
78 exception to be raised if `cond` is not `True`
79 """
80 _CHK_UNEXP = "check_condition() got an unexpected keyword argument {0}"
81
82 raising = kwds.pop("raising", AssertionError)
83 if kwds:
84 raise TypeError(_CHK_UNEXP.format(repr(kwds.popitem()[0])))
85
86 if cond is True:
87 return
88 raise raising(*args)