Esempio n. 1
0
def exceptionAsUnicode(err, add_type=True):
    r"""
    add_type option changes the output for KeyError and exception with an empty
    message (eg. AssertionError). If the option is True (default): add the type
    as prefix, otherwise return an empty string.

    >>> exceptionAsUnicode(Exception("ascii"))
    u'ascii'
    >>> exceptionAsUnicode(Exception("h\xe9 h\xe9"))
    u'h\xe9 h\xe9'
    >>> exceptionAsUnicode(UnicodeException(u"h\xe9 h\xe9"))
    u'h\xe9 h\xe9'
    >>> exceptionAsUnicode(AssertionError())
    u'[AssertionError]'
    >>> exceptionAsUnicode(KeyError(3))
    u'[KeyError] 3'
    >>> exceptionAsUnicode(KeyError(3), False)
    u'3'
    """
    if isinstance(err, (IOError, OSError)) and err.strerror:
        # Get "message" instead of "(42, 'message')"
        return toUnicode(err.strerror)
    if isinstance(err, socket_error):
        # Get 'Connexion refus\xc3\xa9e' instead of
        # (111, 'Connexion refus\xc3\xa9e')
        args = err.args
        if 2 <= len(args):
            msg = args[1]
        else:
            msg = args[0]
        return toUnicode(msg)
    try:
        text = unicode(err)
    except (UnicodeDecodeError, UnicodeEncodeError):
        as_bytes = str(err)
        text = toUnicode(as_bytes)
    if add_type:
        if isinstance(err, KeyError):
            # KeyError message is the key, which is usually meaningless:
            # add [KeyError] prefix
            text = u"[%s] %s" % (err.__class__.__name__, text)
        elif not text:
            # Some errors (eg. AssertionError) have no text, so display the
            # exception type instead of an empty string
            text = u"[%s]" % err.__class__.__name__
    return text
Esempio n. 2
0
def formatTraceback(traceback):
    if not isinstance(traceback, str):
        traceback = format_exception(*traceback)
        if traceback == ["None\n"]:
            return None

        traceback = ''.join(traceback)
    traceback = traceback.rstrip()
    lines = traceback.splitlines()
    return [toUnicode(line) for line in lines]
Esempio n. 3
0
 def __init__(self, message):
     self.unicode_message = toUnicode(message)
     bytes_message = self.unicode_message.encode("ASCII", "replace")
     Exception.__init__(self, bytes_message)