1 |
11
|
aaronmk
|
# Exception handling
|
2 |
|
|
|
3 |
433
|
aaronmk
|
import atexit
|
4 |
343
|
aaronmk
|
import sys
|
5 |
13
|
aaronmk
|
|
6 |
343
|
aaronmk
|
import strings
|
7 |
|
|
import util
|
8 |
|
|
|
9 |
445
|
aaronmk
|
def raise_(e): raise e
|
10 |
|
|
|
11 |
343
|
aaronmk
|
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
|
12 |
|
|
|
13 |
286
|
aaronmk
|
def repl_msg(e, **repls): e.args = (str(e) % repls,)
|
14 |
279
|
aaronmk
|
|
15 |
13
|
aaronmk
|
class ExceptionWithCause(Exception):
|
16 |
|
|
def __init__(self, msg, cause=None):
|
17 |
|
|
Exception.__init__(self, msg)
|
18 |
788
|
aaronmk
|
if cause != None: add_msg(self, 'cause: '+str_(cause))
|
19 |
343
|
aaronmk
|
|
20 |
788
|
aaronmk
|
def str_(e, with_name=True):
|
21 |
343
|
aaronmk
|
msg = strings.ensure_newl(str(e))
|
22 |
|
|
if with_name: msg = util.type_name(e)+': '+msg
|
23 |
788
|
aaronmk
|
return msg
|
24 |
433
|
aaronmk
|
|
25 |
788
|
aaronmk
|
def print_ex(e, **format): sys.stderr.write('! '+str_(e, **format))
|
26 |
|
|
|
27 |
433
|
aaronmk
|
class ExTracker:
|
28 |
|
|
def __init__(self):
|
29 |
|
|
self.e_ct = 0
|
30 |
|
|
def at_exit():
|
31 |
|
|
if self.e_ct > 0:
|
32 |
|
|
raise SystemExit('Encountered '+str(self.e_ct)+' error(s)')
|
33 |
|
|
atexit.register(at_exit)
|
34 |
|
|
|
35 |
|
|
def track(self, e, **format):
|
36 |
|
|
self.e_ct += 1
|
37 |
|
|
print_ex(e, **format)
|