-
Notifications
You must be signed in to change notification settings - Fork 21
/
exceptions.py
74 lines (60 loc) · 1.69 KB
/
exceptions.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
69
70
71
72
73
74
try:
import http.client as httplib
except ImportError:
import httplib
try:
import ujson as json
except:
import json
from . import errors
class TwirpServerException(httplib.HTTPException):
def __init__(self, *args, code, message, meta={}):
if isinstance(code, errors.Errors):
self._code = code
else:
self._code = errors.Errors.Unknown
self._message = message
self._meta = meta
super(TwirpServerException, self).__init__(message)
@property
def code(self):
if isinstance(self._code, errors.Errors):
return self._code
return errors.Errors.Unknown
@property
def message(self):
return self._message
@property
def meta(self):
return self._meta
def to_dict(self):
err = {
"code": self._code.value,
"msg": self._message,
"meta": {}
}
for k, v in self._meta.items():
err["meta"][k] = str(v)
return err
def to_json_bytes(self):
return json.dumps(self.to_dict()).encode('utf-8')
@staticmethod
def from_json(err_dict):
return TwirpServerException(
code=err_dict.get('code', errors.Errors.Unknown),
message=err_dict.get('msg',''),
meta=err_dict.get('meta',{}),
)
def InvalidArgument(*args, argument, error):
return TwirpServerException(
code=errors.Errors.InvalidArgument,
message="{} {}".format(argument, error),
meta={
"argument":argument
}
)
def RequiredArgument(*args, argument):
return InvalidArgument(
argument=argument,
error="is required"
)