Project

General

Profile

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 826 aaronmk
import term
8 343 aaronmk
import util
9
10 445 aaronmk
def raise_(e): raise e
11
12 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
13
14 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
15 279 aaronmk
16 13 aaronmk
class ExceptionWithCause(Exception):
17
    def __init__(self, msg, cause=None):
18
        Exception.__init__(self, msg)
19 788 aaronmk
        if cause != None: add_msg(self, 'cause: '+str_(cause))
20 343 aaronmk
21 788 aaronmk
def str_(e, with_name=True):
22 343 aaronmk
    msg = strings.ensure_newl(str(e))
23
    if with_name: msg = util.type_name(e)+': '+msg
24 788 aaronmk
    return msg
25 433 aaronmk
26 826 aaronmk
def print_ex(e, **format):
27
    emph = format.pop('emph', True)
28
29
    msg = str_(e, **format)
30
    if emph:
31
        first_line, nl, rest = msg.partition('\n')
32
        msg = term.error(first_line)+nl+rest
33
    sys.stderr.write(msg)
34 788 aaronmk
35 433 aaronmk
class ExTracker:
36
    def __init__(self):
37
        self.e_ct = 0
38
        def at_exit():
39
            if self.e_ct > 0:
40
                raise SystemExit('Encountered '+str(self.e_ct)+' error(s)')
41
        atexit.register(at_exit)
42
43
    def track(self, e, **format):
44
        self.e_ct += 1
45
        print_ex(e, **format)