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 973 aaronmk
def print_ex(e, emph=True, **format):
27 826 aaronmk
    msg = str_(e, **format)
28
    if emph:
29
        first_line, nl, rest = msg.partition('\n')
30
        msg = term.error(first_line)+nl+rest
31
    sys.stderr.write(msg)
32 788 aaronmk
33 433 aaronmk
class ExTracker:
34
    def __init__(self):
35
        self.e_ct = 0
36
        def at_exit():
37
            if self.e_ct > 0:
38
                raise SystemExit('Encountered '+str(self.e_ct)+' error(s)')
39
        atexit.register(at_exit)
40
41
    def track(self, e, **format):
42
        self.e_ct += 1
43
        print_ex(e, **format)