source: sasmodels/sasmodels/exception.py @ 71b751d

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 71b751d was 4d76711, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

adjust interface to sasview

  • Property mode set to 100644
File size: 1.4 KB
Line 
1"""
2Utility to add annotations to python exceptions.
3"""
4import sys
5
6# Platform cruft: WindowsError is only defined on Windows.
7try:
8    WindowsError
9except NameError:
10    class WindowsError(Exception):
11        """
12        Fake WindowsException when not on Windows.
13        """
14        pass
15
16def annotate_exception(msg, exc=None):
17    """
18    Add an annotation to the current exception, which can then be forwarded
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.
22
23    Example::
24
25        >>> D = {}
26        >>> try:
27        ...    print(D['hello'])
28        ... except:
29        ...    annotate_exception("while accessing 'D'")
30        ...    raise
31        Traceback (most recent call last):
32            ...
33        KeyError: "hello while accessing 'D'"
34    """
35    if not exc:
36        exc = sys.exc_info()[1]
37
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):
41        raise OSError(str(exc) + " " + msg)
42
43    args = exc.args
44    if not args:
45        exc.args = (msg,)
46    else:
47        try:
48            arg0 = " ".join((args[0], msg))
49            exc.args = tuple([arg0] + list(args[1:]))
50        except:
51            exc.args = (" ".join((str(exc), msg)),)
Note: See TracBrowser for help on using the repository browser.