ManifoldAPI raises ManifoldException if anything goes wrong
[myslice.git] / manifold / manifoldresult.py
1 def enum(*sequential, **named):
2     enums = dict(zip(sequential, range(len(sequential))), **named)
3     return type('Enum', (), enums)
4
5 ManifoldCode = enum (
6     SUCCESS=0,
7     SESSION_EXPIRED=1,
8     NOT_IMPLEMENTED=2,
9     UNKNOWN_ERROR=3,
10 )
11
12 # being a dict this can be used with json.dumps
13 class ManifoldResult (dict):
14     def __init__ (self, code=ManifoldCode.SUCCESS, value=None, output=""):
15         self['code']=code
16         self['value']=value
17         self['output']=output
18
19     def from_json (self, json_string):
20         d=json.dumps(json_string)
21         for k in ['code','value','output']:
22             self[k]=d[k]
23
24     # raw accessors
25     def code (self): return self['code']
26     def output (self): return self['output']
27
28     # this returns None if there's a problem, the value otherwise
29     def ok_value (self):
30         if self['code']==ManifoldCode.SUCCESS:
31             return self['value']
32
33     # both data in a single string
34     def error (self):
35         return "code=%s -- %s"%(self['code'],self['output'])
36     
37
38     def __repr__ (self):
39         result="[[MFresult code=%s"%self['code']
40         if self['code']==0:
41             value=self['value']
42             if isinstance(value,list): result += " [value=list with %d elts]"%len(value)
43             else: result += " [value=other %s]"%value
44         else:
45             result += " [output=%s]"%self['output']
46         result += "]]"
47         return result
48
49 # probably simpler to use a single class and transport the whole result there
50 # instead of a clumsy set of derived classes 
51 class ManifoldException (Exception):
52     def __init__ (self, manifold_result):
53         self.manifold_result=manifold_result
54     def __repr__ (self):
55         return "Manifold Exception %s"%(self.manifold_result.error())