Repository navigation
Expand file tree
/
Copy pathtrywrappers.py
More file actions
executable file
·350 lines (267 loc) · 13.6 KB
/
Copy pathtrywrappers.py
File metadata and controls
executable file
·350 lines (267 loc) · 13.6 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
##############################################################################
# Removal of the "__license__" line or content from "__license__", or removal
# of "__author__" in this or any constituent # component or file constitutes a
# violation of the licensing and copyright agreement.
__author__ = "Mike Rightmire"
__copyright__ = "BioCom Software"
__license__ = "Telemend"
__license_file__= "Clause1.PERPETUAL_AND_UNLIMITED_LICENSING_TO_THE_CLIENT.py"
__version__ = "0.9.6.0"
__maintainer__ = "Mike Rightmire"
__email__ = "Mike.Rightmire@BiocomSoftware.com"
__status__ = "Development"
##############################################################################
import functools
# from errorhandler import ErrorHandler
def raisetry(key):
"""
:NAME:
raisetry(key)
:DESCRIPTION:
raisetry is a decorator which functions to customize the try/except
paradigm in Python by attaching the parameter "key" to the raised
exception.
:ARGUMENTS:
key: A string which is added to the raised error message.
:RETURNS:
Raises an exception
:USAGE:
@raisetry("Class.method: Attempting to open " + str(invalidfilename))
FH = open("invalidfilename, "r+", 0)
---------------------
The above replaces...
---------------------
key = "Class.method: Attempting to open " + str(invalidfilename)
try:
FH = open("invalidfilename, "r+", 0)
except Exception as err:
if not err.args:
err.args=('',)
err.args = (
(cls + "." + module + ": " + key + ". " + err.args[0],) +
err.args[1:]
)
raise
"""
def concrete_decorator(func):
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
cls = str(self.__class__.__name__)
module = func.__name__
try:
result = func(self, *args, **kwargs)
return result
except Exception as err:
err = _dress_msg(cls, module, key, err, args, kwargs)
raise
return wrapped
return concrete_decorator
def handlertry(key = "", maxtries = 1):
"""
:NAME:
handlertry([key, maxtries = n])
:DESCRIPTION:
handlertry is a decorator which customizes the try/except
paradigm in Python. The "key" parameter is mandatory, but can be passed
either as a parameter in the decorator statement, or included in the
error message body.
The key is "human readable signal phrase" which is passed to the
ErrorHandler.customErr method. The 'key' parameter can also be omitted
and the "signal phrase" can be included in the error message itself.
The customErr method in turn uses the phrase to send control to the
appropriate ErrorHandler.handlers.<method>. This method then
determines the additional processing (if any) to be done in an attempt
to correct the problem that raised the error.
At each iteration of the ErrorHandler.handlers.<method>, 'handlertry'
receives back the parameter 'final' (True/False) which determines if
another iteration of the original decorated method is tried. If final is
False (and 'maxtries' has not been reached) the decorator will attemot
to run another iteration of the original decorated method. If 'final' is
True, the original error generated by the decorated method is raised.
IT IS THE DEVELOPER'S JOB to be sure to return 'final=True/False' from
the error handler function. Failure to do so will result in continued
looping until the maxtries limit is reached.
The "maxtries" parameter determines how many times the original
decorated function will be re-run, if a 'final = True' is not received
from the handler function by the decorator. When 'maxtries' is reached,
the decorator will no longer attempt to call the original function
regardless or whether 'final' si set.
'maxtries' defaults to three (3) attempts.
I.e.
class originalclass(object);
def __init__(sekf):
pass
@handlertry('myhandler', maxtries = 3)
def originalmethod(self):
raise AttributeError('This was dumb')
1. originalclass.originalmethod is passed to the handlertry decorator
2. originalmethod is tried, but raises the error (this is try one)
3. Error passed to ErrorHandler.handlers.myhandler()
4. ErrorHandler.handlers.myhandler() tries to fix the problem (for
example, asks for additional input), and passes control back to the
handlertry decorator.
5. handlertry tries to run originalmethod again, and errors again (I.e.
the fix did not work)
6. ErrorHandler.handlers.myhandler() tries to fix the problem again
(try 2, step 5 again). If the method works this time, control is
return'ed back to originalclass.originalmethod, meaning the original
method is returned and control is AT THE LINE FOLLOWING THE END OF
originalmethod.
7. If it fails, Repeat 5 & 6 (try 3)
8. Regardless of whether the issue was fixed or not, since try 3 was
the last try - the oringinal error is raised for alternate handling.
:ARGUMENTS:
key: A string which is added to the raised error message.
This string should contain a "trigger message" to allow
handlertry to drop control to a pre-defined routine to either
correct the error or prep the package for controlled shutdown.
If the key is "", ErrorHandler.UnknownException is used.
maxtries: The maximum number of times to attempt to run the decorated
function regardless of success or the 'final' variable being
passed.
If the decorated function SUCCEEDS, control is
returned AFTER to the original calling method.
If the decorated method FAILS, control is passed to the
ErrorHandler class which attempts to fix the problem, and
re-runs the decorated function.
When "maxtries" is exceeded, control is returned after
the original calling method, REGARDLESS of whether the issue was
fixed or not.
Control is always returned to THE LINE FOLLOWING THE NORMAL
RETURN OF THE DECORATED METHOD.
'maxtries' DEFAULTS TO: 3
:RETURNS:
handlertry returns three arguments: the original args and kwargs passed
to handlertry, INCLUDING ANY CHANGES made by the handler method; and a
"result" which can be anything. The 'result' return is simply passed
back from handlertry to the decorated function.
:USAGE:
=========================================================
Currently, these handlers only work within class objects.
=========================================================
STEP ONE: The @handlertry decorator must be added to the main
body of the code to be handled.
The @handlertry system can be used in code in three ways:
1. In this form , the 'TriggerMessage' handles the entire method.
In this case, any error will be handled by the handlertry, and
there is no need for an additional try/except.
class myclass(object):
def __init__(self):
pass
@handlertry("TriggerMessage: ", maxtries = 2)
def myMethod(self, args, kwargs):
FH = open(filename, "w+", 0)
return FH
<Some more code here. control always returns here>
2. In the following, @handlertry is left generic, and the TriggerMessage
is passed through the error message. In this case, a try/except
must be included to add the TriggerMessage to the error.
@handlertry()
def myMethod(self, args, kwargs)::
try:
FH = open(filename, "w+", 0)
return FH
except (Exception, Exception) as e:
e.message = ('TriggerMessage: ' + e.message)
raise type(e)(e.message)
<Some more code here. control always returns here>
3. Use a generic @tryhandler, and simply call an exception with
the TriggerMessage as the entire custom message.
@handlertry("")
def myMethod(self, args, kwargs)::
if a == b:
<perform code>
else:
raise Exception('TriggerMessage')
<Some more code here. control always returns here>
------------------------
The above results in ...
------------------------
1. Attempting to run the line of code 'FH = open("invalidfilename, "r+", 0)'
2. On error, control is passed to 'ErrorHandler.handlers.TriggerMessage()',
which has been written by the developer to handle this situation.
3a.If the TriggerMessage handler can correct the issue, control is passed
back to the calling script, at the line FOLLOWING the completion of the
originally decorated METHOD and code continues to run.
3b.If the TriggerMessage handler CANNOT correct the issue, it can continue
to try and fix the issue, and re-run the decorated method, for "maxtries"
number of attempts, or until the TriggerMessage() handler sets
'final' = True. Control is then passed back to the line
following the decorated method.
"""
try:
maxtries = int(maxtries)
if maxtries < 1: maxtries = 1
except ValueError as e:
maxtries = 1
def concrete_decorator(func):
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
#----------------------------------------------------------------
# In this def, 'self' refers to the object that called handlertry
#----------------------------------------------------------------
# Must import here and not in the pre-script area
import errorhandler
from inspect import getmembers, stack
CustomErrorHandler = errorhandler.ErrorHandler()
# handler = CustomErrorHandler.err()
cls = str(self.__class__.__name__)
module = func.__name__
# Success is set in the try:except below
success = False
# final gets set by the response from the CustomErrorHandler.customErr
final = False
tally = 1 # First try
result = None
while ((success is False) and (tally <= maxtries)):
try:
result = func(self, *args, **kwargs)
success = True
except Exception as err: # err not e
if final is not False:
raise err # err not e
else:
e = _dress_msg(cls, module, key, err, args, kwargs)
args, kwargs, final, result = CustomErrorHandler.customErr(
self,
tally,
args,
kwargs,
e,
getmembers(self),
stack()
)
tally += 1
return result
return wrapped
return concrete_decorator
def _dress_msg(cls, module, key, err, args, kwargs):
# kluge in the case an old style message is passed
try:
err = str(err.args[0])
except Exception, e:
err = str(err)
# This worked before, but not on the PI
# if not err.args:
# err.args=('',)
if len(args) == 0:
args = None
if len(kwargs) == 0:
kw = None
else:
kw = ""
for key in kwargs.keys():
kw = kw + "'" + str(key) + ":" + str(kwargs[key]) + "', "
kw = kw[:len(kw) - 2]
err = ''.join([cls, ".", module,": ",
key,
"; *args: ",
str(args) +
"; **kwargs: ",
str(kw),
"; ",
err
])
return err
if __name__ == "__main__":
print "no test"