예제 #1
0
class UserError(Exception):
    """
    user errors should be caught and re-thrown with this
    Be warned that this exception can throw an exception.  Yes, you read that right.  I apologize in advance.
    :raises: ValueError (varsSoFar gets pickled into JSON, which may result in any number of errors depending on what types are inside)
    """
    def __init__(self, exc_obj, exc_tb, varsSoFar={}, execTime=0):
        # skip arepl traceback - the user should just see their own error
        exc_tb = exc_tb.tb_next

        self.traceback_exception = TracebackException(type(exc_obj), exc_obj,
                                                      exc_tb)
        self.friendly_message = "".join(self.traceback_exception.format())
        self.varsSoFar = pickle_user_vars(varsSoFar,
                                          get_settings().default_filter_vars,
                                          get_settings().default_filter_types)
        self.execTime = execTime

        # stack is empty in event of a syntax error
        # This is problematic because frontend has to handle syntax/regular error differently
        # to make it easier populate stack so frontend can handle them the same way
        if self.traceback_exception.exc_type is SyntaxError:
            self.traceback_exception.stack.append(
                FrameSummary(self.traceback_exception.filename,
                             int(self.traceback_exception.lineno), ""))
예제 #2
0
 def from_exc_info(cls, artifact_name, exc_info):
     te = TracebackException(*exc_info)
     # NB: we have dropped werkzeug's support for Paste's __traceback_hide__
     # frame local.
     return cls(
         {
             "artifact": artifact_name,
             "exception": "".join(te.format_exception_only()).strip(),
             "traceback": "".join(te.format()).strip(),
         }
     )
예제 #3
0
def parse_exception(exc, extra_msg=''):
    if not exc:
        return []
    exc_list = exc
    if isinstance(exc, Exception):
        tbe = TracebackException(type(exc), exc, exc.__traceback__)
        exc_list = tbe.format()
    lines = []
    for l in exc_list:
        lines.extend(l.split('\n'))
    lines.append(extra_msg)
    return list(map(lambda x: x.strip(), filter(lambda x: x, lines)))
예제 #4
0
def format_exc(exc=None):
    """Format an exception to be printed"""
    from sys import exc_info
    from traceback import TracebackException
    from itertools import chain
    if exc is None:
        exc = exc_info()
    tbe = TracebackException(*exc, limit=None, capture_locals=True)
    itr = chain.from_iterable(
        lin.split('\n') for lin in tbe.format(chain=None))
    title = (next(itr), '  Globals:')  # pylint: disable=R1708
    globals_ = exc[2].tb_frame.f_globals
    globals_ = ('    {} = {}'.format(k, v) for k, v in globals_.items())
    yield from chain(title, globals_, (i for i in itr if i != ''))
예제 #5
0
def error_window(exc: TracebackException):
    message = ''.join(exc.format())

    layout = [[sg.Text(message)], [sg.Button('Ok')]]

    window = sg.Window('Error', layout)

    # --------------------- EVENT LOOP ---------------------
    while True:
        event, values = window.Read(
            timeout=100)  # wait for up to 100 ms for a GUI event
        if event is None or event == 'Ok':
            break

    # if user exits the window, then close the window and exit the GUI func
    window.Close()
예제 #6
0
def mprint_exc(scrub_exc_msg=True, file=sys.stderr):
    '''Print exception to StdErr of AEther client.
    By defaut, it scrub exception message, print traceback and exception type.
    :param bool scrub_exc_msg: wheather scrub exception message.
    '''
    tb_exc = TracebackException(*sys.exc_info())
    if scrub_exc_msg:
        tb_exc = scrub_exc_message(tb_exc)
    exc_list = list(tb_exc.format())
    for exc in exc_list:
        if "return function(*matrix_args, **matrix_kwargs)" in exc:
            # dow not show Traceback for compliant_handle
            continue
        lines = exc.splitlines()
        for line in lines:
            timestamp = datetime.datetime.strftime(datetime.datetime.now(),
                                                   '%Y-%m-%d %H:%M:%S')
            print("SystemLog: [%s] %s" % (timestamp, line), file=file)
예제 #7
0
def _traceback_to_str(traceback: TracebackException) -> str:
    exception_trace_as_str = ""
    for line in traceback.format(chain=False):
        exception_trace_as_str += line
    return exception_trace_as_str
예제 #8
0
class Traceback(object):
    """Wraps a traceback."""

    def __init__(self, exc_type, exc_value, tb):
        self.exc_type = exc_type
        self.exc_value = exc_value
        if not isinstance(exc_type, str):
            exception_type = exc_type.__name__
            if exc_type.__module__ not in ('__builtin__', 'exceptions'):
                exception_type = exc_type.__module__ + '.' + exception_type
        else:
            exception_type = exc_type
        self.exception_type = exception_type
        self.te = TracebackException(exc_type, exc_value, tb)

        def get_ext_frames(ext_expt, ext_expt_value):
            ext_tb = ext_expt.exc_traceback
            ext_exc_type = ext_expt.exc_type
            self.ext_frames = []
            while ext_tb:
                self.ext_frames.append(Frame(ext_exc_type, ext_expt_value, ext_tb))
                ext_tb = ext_tb.tb_next

        if self.te.__cause__ is not None:
            get_ext_frames(self.te.__cause__, exc_value.__cause__)
        elif self.te.__context__ is not None and \
                not self.te.__suppress_context__:
            get_ext_frames(self.te.__context__, exc_value.__context__)
            
        # we only add frames to the list that are not hidden.  This follows
        # the the magic variables as defined by paste.exceptions.collector
        self.frames = []
        while tb:
            self.frames.append(Frame(exc_type, exc_value, tb))
            tb = tb.tb_next

    def filter_hidden_frames(self):
        """Remove the frames according to the paste spec."""
        if not self.frames:
            return

        new_frames = []
        hidden = False
        for frame in self.frames:
            hide = frame.hide
            if hide in ('before', 'before_and_this'):
                new_frames = []
                hidden = False
                if hide == 'before_and_this':
                    continue
            elif hide in ('reset', 'reset_and_this'):
                hidden = False
                if hide == 'reset_and_this':
                    continue
            elif hide in ('after', 'after_and_this'):
                hidden = True
                if hide == 'after_and_this':
                    continue
            elif hide or hidden:
                continue
            new_frames.append(frame)

        # if we only have one frame and that frame is from the codeop
        # module, remove it.
        if len(new_frames) == 1 and self.frames[0].module == 'codeop':
            del self.frames[:]

        # if the last frame is missing something went terrible wrong :(
        elif self.frames[-1] in new_frames:
            self.frames[:] = new_frames

    @property
    def is_syntax_error(self):
        """Is it a syntax error?"""
        return isinstance(self.exc_value, SyntaxError)

    @property
    def exception(self):
        """String representation of the exception."""
        buf = traceback.format_exception_only(self.exc_type, self.exc_value)
        rv = ''.join(buf).strip()
        return rv.decode('utf-8', 'replace') if PY2 else rv

    def log(self, logfile=None):
        """Log the ASCII traceback into a file object."""
        if logfile is None:
            logfile = sys.stderr
        tb = self.plaintext.rstrip() + u'\n'
        if PY2:
            tb = tb.encode('utf-8', 'replace')
        logfile.write(tb)

    def paste(self):
        """Create a paste and return the paste id."""
        data = json.dumps({
            'description': 'Werkzeug Internal Server Error',
            'public': False,
            'files': {
                'traceback.txt': {
                    'content': self.plaintext
                }
            }
        }).encode('utf-8')
        try:
            from urllib2 import urlopen
        except ImportError:
            from urllib.request import urlopen
        rv = urlopen('https://api.github.com/gists', data=data)
        resp = json.loads(rv.read().decode('utf-8'))
        rv.close()
        return {
            'url': resp['html_url'],
            'id': resp['id']
        }

    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ''
        frames = []
        ext_frames_html = ''
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = u'Syntax Error'
            else:
                title = u'Traceback <em>(most recent call last)</em>:'

        if hasattr(self, 'ext_frames'):
            ext_frames = []
            for frame in self.ext_frames:
                ext_frames.append(u'<li%s>%s' % (
                    frame.info and u' title="%s"' % escape(frame.info) or u'',
                    frame.render()
                ))
            reason = traceback._cause_message if self.te.__cause__ is not None else traceback._context_message
            ext_frames_html = EXT_FRAMES_HTML % {
                'frames': u'\n'.join(ext_frames),
                'reason': reason
            }

        for frame in self.frames:
            frames.append(u'<li%s>%s' % (
                frame.info and u' title="%s"' % escape(frame.info) or u'',
                frame.render()
            ))

        if self.is_syntax_error:
            description_wrapper = u'<pre class=syntaxerror>%s</pre>'
        else:
            description_wrapper = u'<blockquote>%s</blockquote>'

        return SUMMARY_HTML % {
            'classes':      u' '.join(classes),
            'title':        title and u'<h3>%s</h3>' % title or u'',
            'ext_frames':   ext_frames_html,
            'frames':       u'\n'.join(frames),
            'description':  description_wrapper % escape(self.exception)
        }

    def render_full(self, evalex=False, secret=None,
                    evalex_trusted=True):
        """Render the Full HTML page with the traceback info."""
        exc = escape(self.exception)
        return PAGE_HTML % {
            'evalex':           evalex and 'true' or 'false',
            'evalex_trusted':   evalex_trusted and 'true' or 'false',
            'console':          'false',
            'title':            exc,
            'exception':        exc,
            'exception_type':   escape(self.exception_type),
            'summary':          self.render_summary(include_title=False),
            'plaintext':        escape(self.plaintext),
            'plaintext_cs':     re.sub('-{2,}', '-', self.plaintext),
            'traceback_id':     self.id,
            'secret':           secret
        }

    @property
    def plaintext(self):
        return u''.join(self.te.format())

    id = property(lambda x: id(x))