-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathError.py
68 lines (49 loc) · 2 KB
/
Error.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Universal error class."""
class Error(dict):
"""Universal error class.
An error is a dictionary-like object, containing a specific
user-readable error message and an object associated with it.
Since Error inherits dict, other informative values can be arbitrarily
attached to errors. For this reason, subclassing Error is rare.
Example::
err = Error(user, 'Invalid password.')
err['time'] = time.time()
err['attempts'] = attempts
The object and message can be accessed via methods::
print(err.object())
print(err.message())
When creating errors, you can pass None for both object and message.
You can also pass additional values, which are then included in the error::
>>> err = Error(None, 'Too bad.', timestamp=time.time())
>>> err.keys()
['timestamp']
Or include the values as a dictionary, instead of keyword arguments::
>>> info = {'timestamp': time.time()}
>>> err = Error(None, 'Too bad.', info)
Or you could even do both if you needed to.
"""
def __init__(self, obj, message, valueDict=None, **valueArgs):
"""Initialize the error.
Takes the object the error occurred for, and the user-readable
error message. The message should be self sufficient such that
if printed by itself, the user would understand it.
"""
dict.__init__(self)
self._object = obj
self._message = message
if valueDict:
self.update(valueDict)
self.update(valueArgs)
def object(self):
"""Get the object the error occurred for."""
return self._object
def message(self):
"""Get the user-readable error message."""
return self._message
def __repr__(self):
return (f'ERROR(object={self._object!r};'
f' message={self._message!r}; data={dict(self)!r})')
def __str__(self):
return f'ERROR: {self._message}'
def __bool__(self):
return True