Extended system hook for exceptions.

    supports logging of tracebacks to a file

    lets fnc() be executed imediately before the IPython
    Verbose Traceback is started

    this can be used to pop up a QTMessageBox: "An exception occured"
171324
def ip_extra_syshook(fnc, pdb=0, filename=None):
    

    assert isinstance(fnc, collections.Callable)
    from IPython.core import ultratb
    import time

    if not filename == None:
        assert isinstance(filename, str)
        pdb = 0

    ip_excepthook = ultratb.FormattedTB(mode='Verbose',
                                    color_scheme='Linux', call_pdb=pdb)

    fileTraceback = ultratb.FormattedTB(mode='Verbose',
                                    color_scheme='NoColor', call_pdb=0)

    # define the new excepthook
    def theexecpthook (type, value, traceback):
        fnc()
        ip_excepthook(type, value, traceback)
        # write this to a File without Colors
        if not filename == None:
            outFile = open(filename, "a")
            outFile.write("--" + time.ctime()+" --\n")
            outFile.write(fileTraceback.text(type, value, traceback))
            outFile.write("\n-- --\n")
            outFile.close()

    # assign it
    sys.excepthook = theexecpthook
179070
def _install_exception_handler(self):
        
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))

        sys.excepthook = handler
427300
def exception_handler(exctype, value, traceback):
    
    if exctype == KeyboardInterrupt:
        pypro.console.out('')  # Adds a new line after Ctrl+C character
        pypro.console.err('Canceled')
    elif exctype == PyproException:
        pypro.console.err('[Error] ', value.message)
        exit()
    else:
        sys.__excepthook__(exctype, value, traceback)
894686
def exception(self, exception):
        """"""
        if self.writelog:
            self.logger.exception(exception)
        if self.verbose:
            for line in  traceback.format_exception(
                    None, exception, exception.__traceback__):
                print(line, end='', file=sys.stderr, flush=True)
279829
def _show_traceback(method):
    """"""
    def m(self, *args, **kwargs):
        try:
            return(method(self, *args, **kwargs))
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                self.log.warning("Exception in widget method %s: %s", method, e, exc_info=True)
            else:
                ip.showtraceback()
    return m
239958
def withTracebackPrint(ErrorType, thrownError, _traceback):
    ''''''
    file = StringIO.StringIO()
    traceback.print_exception(ErrorType, thrownError, _traceback, file = file)
    return _loadError(ErrorType, thrownError, file.getvalue())
90253
def _exception_free_callback(self, callback, *args, **kwargs):
        
        try:
            return callback(*args, **kwargs)
        except Exception:
            self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
            return None
1049396
def template_exception_handler(fn, error_context, filename=None):
    """"""
    error_message = None
    if filename:
        error_context.update(filename=filename)
    try:
        return fn()
    except jinja2.TemplateSyntaxError as exc:
        error_context.update(filename=exc.filename, line_no=exc.lineno)
        error_message = exc.message
    except jinja2.TemplateError as exc:
        error_message = exc.message
    except Exception as exc:
        error_message = "%s" % exc

    raise TemplateError(message=error_message, context=error_context)
619768
def ExceptionHook(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
1275270
def _log_exception(self, exception):
        
        self._io.error(str(exception).strip().split(os.linesep))
1037632
def catch(ignore=[],
          was_doing="something important",
          helpfull_tips="you should use a debugger",
          gbc=None):
    
    exc_cls, exc, tb=sys.exc_info()
    if exc_cls in ignore:
        msg='exception in ignorelist'
        gbc.say('ignoring caught:'+str(exc_cls))
        return 'exception in ignorelist'
        

    ex_message = traceback.format_exception_only(exc_cls, exc)[-1]
    ex_message = ex_message.strip()
    
    # TODO: print(ex_message)

    error_frame = tb
    while error_frame.tb_next is not None:
        error_frame = error_frame.tb_next

    file = error_frame.tb_frame.f_code.co_filename
    line = error_frame.tb_lineno
    stack = traceback.extract_tb(tb)

    formated_stack = []
    for summary in stack:
        formated_stack.append({
            'file': summary[0],
            'line': summary[1],
            'func': summary[2],
            'text': summary[3]
        })

    event = {
        'was_doing':was_doing,
        'message': ex_message,
        'errorLocation': {
            'file': file,
            'line': line,
            'full': file + ' -> ' + str(line)
        },
        'stack': formated_stack
        #,
        #'time': time.time()
    }

    try:
        #logging.info('caught:'+pformat(event))
        gbc.cry('caught:'+pformat(event))
        print('Bubble3: written error to log')
        print('Bubble3: tips for fixing this:')
        print(helpfull_tips)

    except Exception as e:
        print('Bubble3: cant log error cause of %s' % e)
923145
def trace_error(function_index=2):
    
    info = function_info(function_index)
    traces = traceback.format_stack(limit=10)
    for trace in traces:
        file_, line_number, line_text = trace.split(',', 2)
        if file_ == '  File "%s"' % info['file'] and\
                        line_number != 'line %s' % info['line_number']:
            return line_number.split()[-1], line_text.strip()
    return None, None
1181297
def format_exception(self):
        
        import traceback
        frames = self.get_traceback_frames()
        tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
        list = ['Traceback (most recent call last):\n']
        list += traceback.format_list(tb)
        list += traceback.format_exception_only(self.exc_type, self.exc_value)
        return list
1061214
def ExceptionHookPDB(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
    pdb.pm()
936316
def user_exception(self, frame, exc_info):
        """"""
        exc_type, exc_value, exc_traceback = exc_info
        frame.f_locals['__exception__'] = exc_type, exc_value

        # An 'Internal StopIteration' exception is an exception debug event
        # issued by the interpreter when handling a subgenerator run with
        # 'yield from' or a generator controled by a for loop. No exception has
        # actually occured in this case. The debugger uses this debug event to
        # stop when the debuggee is returning from such generators.
        prefix = 'Internal ' if (PY34 and not exc_traceback
                                    and exc_type is StopIteration) else ''
        self.message('--Exception--\n%s%s' % (prefix,
            traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
        self.interaction(frame, exc_traceback)
268795
def handleError(exception, debugFlag=False, abortFlag=True):
    """"""
    if isinstance(exception, CmdError) or not debugFlag:
        error(str(exception))
    else:
        import traceback
        traceback.print_exc()
        error(str(exception))   # or log complete traceback as well?
    if abortFlag:
        sys.exit(1)
645754
def report_exception(self, filename, exc):
        
        # Build fake event.
        event = AbinitError(src_file="Unknown", src_line=0, message=str(exc))
        return EventReport(filename, events=[event])