Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5

    
6
import strings
7
import term
8
import util
9

    
10
def raise_(e): raise e
11

    
12
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
13

    
14
def repl_msg(e, **repls): e.args = (str(e) % repls,)
15

    
16
class ExceptionWithCause(Exception):
17
    def __init__(self, msg, cause=None):
18
        Exception.__init__(self, msg)
19
        if cause != None: add_msg(self, 'cause: '+str_(cause))
20

    
21
def str_(e, with_name=True):
22
    msg = strings.ensure_newl(str(e))
23
    if with_name: msg = util.type_name(e)+': '+msg
24
    return msg
25

    
26
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

    
35
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)
(5-5/14)