source:
sasmodels/sasmodels/exception.py
@
68f45cb
Last change on this file since 68f45cb was 4d76711, checked in by Paul Kienzle <pkienzle@…>, 8 years ago | |
---|---|
|
|
File size: 1.4 KB |
Rev | Line | |
---|---|---|
[9e430d0] | 1 | """ |
2 | Utility to add annotations to python exceptions. | |
3 | """ | |
[4d76711] | 4 | import sys |
[9e430d0] | 5 | |
[0763009] | 6 | # Platform cruft: WindowsError is only defined on Windows. |
7 | try: | |
8 | WindowsError | |
9 | except NameError: | |
10 | class WindowsError(Exception): | |
[823e620] | 11 | """ |
12 | Fake WindowsException when not on Windows. | |
13 | """ | |
[0763009] | 14 | pass |
15 | ||
[4d76711] | 16 | def annotate_exception(msg, exc=None): |
[9e430d0] | 17 | """ |
18 | Add an annotation to the current exception, which can then be forwarded | |
[4d76711] | 19 | to the caller using a bare "raise" statement to raise the annotated |
20 | exception. If the exception *exc* is provided, then that exception is the | |
21 | one that is annotated, otherwise *sys.exc_info* is used. | |
[d138d43] | 22 | |
[9e430d0] | 23 | Example:: |
[d138d43] | 24 | |
[9e430d0] | 25 | >>> D = {} |
26 | >>> try: | |
[9404dd3] | 27 | ... print(D['hello']) |
[4d76711] | 28 | ... except: |
29 | ... annotate_exception("while accessing 'D'") | |
[9e430d0] | 30 | ... raise |
31 | Traceback (most recent call last): | |
32 | ... | |
33 | KeyError: "hello while accessing 'D'" | |
34 | """ | |
[4d76711] | 35 | if not exc: |
36 | exc = sys.exc_info()[1] | |
37 | ||
[0763009] | 38 | # Can't extend WindowsError exceptions; instead raise a new exception. |
39 | # TODO: try to incorporate current stack trace in the raised exception | |
40 | if isinstance(exc, WindowsError): | |
[823e620] | 41 | raise OSError(str(exc) + " " + msg) |
[0763009] | 42 | |
[9e430d0] | 43 | args = exc.args |
44 | if not args: | |
45 | exc.args = (msg,) | |
46 | else: | |
47 | try: | |
[823e620] | 48 | arg0 = " ".join((args[0], msg)) |
[9e430d0] | 49 | exc.args = tuple([arg0] + list(args[1:])) |
50 | except: | |
[823e620] | 51 | exc.args = (" ".join((str(exc), msg)),) |
Note: See TracBrowser
for help on using the repository browser.