Beispiel #1
0
 def handle(self, method, **arguments):
     """ handle means handling tasks. the result is always json """
     self.set_global_state()
     self.last_access = time.time()
     try:
         return self.tk.handle(method, **arguments)
     except Exception, e:
         self.crashed = True
         self.traceback = cgitb.html(sys.exc_info())
         if self.debug:
             print "A session crashed. Since you're running in debug mode, here's a traceback!"
             print
             print cgitb.text(sys.exc_info())
 def test_text(self):
     try:
         raise ValueError("Hello World")
     except ValueError as err:
         text = cgitb.text(sys.exc_info())
         self.assertIn("ValueError", text)
         self.assertIn("Hello World", text)
Beispiel #3
0
 def _generatePlainErrorEmail(self):
     """
     Generates the plain-text version of the error email. Must return a
     string.
     """
     import cgitb
     return cgitb.text(sys.exc_info())
Beispiel #4
0
def text_traceback():
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        res = 'the original traceback:'.join(
            cgitb.text(sys.exc_info()).split('the original traceback:')[1:]
        ).strip()
    return res
Beispiel #5
0
    def handle_error():
        etype, evalue, etb = sys.exc_info()
        eclass = str if isinstance(etype, basestring) else etype
        if issubclass(eclass, KeyboardInterrupt): raise
        if issubclass(eclass, StopIteration): raise  # let it propagate
        if issubclass(eclass, GeneratorExit): raise  # let the generator die
        if issubclass(eclass, FilingFormatNotDocumented):
            # We don't bother to log these; we know they happen.
            return

        pathname = cover_record.get('pathname')
        report_id = cover_record.get('this_report_id')

        logdir = os.path.join(destdir, 'errors')
        if not os.path.exists(logdir): os.makedirs(logdir)
        fd, path = tempfile.mkstemp(dir=logdir, suffix='.' + eclass.__name__)
        fo = os.fdopen(fd, 'w')
        lines_of_context = 5
        fo.write(
            'Surprise; last filing successfully opened was\n%s in %s\n\n' %
            (report_id, pathname))
        fo.write(cgitb.text((etype, evalue, etb), lines_of_context))
        fo.close()

        sys.stderr.write("logged error (in %s?) to %s, continuing\n" %
                         (report_id, path))
Beispiel #6
0
def excepthook(etype, value, tb):
    # Added this line for debugging why https://travis-ci.org/cubing/tnoodle/builds/15966902
    # hit pdb instead of just printing a traceback and exiting.
    # Once that problem is solved, we can delete this code.
    print(
        "Hit excepthook! stderr.isatty: %s stdin.isatty: %s stdout.isatty: %s"
        % (sys.stderr.isatty(), sys.stdin.isatty(), sys.stdout.isatty()))

    # Workaround for isatty weirdness mentioned above.
    isTravisCiBuild = os.environ.get('TRAVIS_BRANCH', None)
    if not sys.stdout.isatty() or not sys.stderr.isatty(
    ) or not sys.stdin.isatty() or isTravisCiBuild:
        # We're not running interactively, so don't enter PDB.
        sys.stderr.write(cgitb.text((etype, value, tb)))

        while tb.tb_next:
            tb = tb.tb_next
        sys.stderr.write("Globals: {}\n".format(tb.tb_frame.f_locals))
        sys.stderr.write("Locals: {}\n".format(tb.tb_frame.f_locals))
    else:
        if tb:
            traceback.print_exception(etype, value, tb)
        if Throwable and issubclass(etype, Throwable):
            value.printStackTrace()
        pdb.post_mortem(tb)
 def test_text(self):
     try:
         raise ValueError('Hello World')
     except ValueError as err:
         text = cgitb.text(sys.exc_info())
         self.assertIn('ValueError', text)
         self.assertIn('Hello World', text)
Beispiel #8
0
	def notify_error(self):
		ex_type, ex, tb = sys.exc_info()
		self.send_html({ 
			'subject': 'Fatal Error',
			'html': cgitb.html(sys.exc_info()),
			'text': cgitb.text(sys.exc_info())
		})
Beispiel #9
0
def text_traceback():
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        res = 'the original traceback:'.join(
            cgitb.text(
                sys.exc_info()).split('the original traceback:')[1:]).strip()
    return res
Beispiel #10
0
def my_except_hook(etype, evalue, etraceback):
    """
    Super verbose unhandled exception information. from
    http://boodebr.org/main/python/tourist/taking-exception
    """
    txt = cgitb.text( (etype,evalue,etraceback) )
    ok("** EXITING on unhandled exception \n%s" % txt,False)
    def errorLog(self, sError, aXcptInfo, sLogFile):
        """
        Writes the error to a log file.
        """
        # Easy solution for log file size: Only one report.
        try:
            os.unlink(sLogFile)
        except:
            pass

        # Try write the log file.
        fRc = True
        fSaved = self._fHtmlDebugOutput

        try:
            oFile = open(sLogFile, 'w')
            oFile.write(sError + '\n\n')
            if aXcptInfo[0] is not None:
                oFile.write(' B a c k t r a c e\n')
                oFile.write('===================\n')
                oFile.write(cgitb.text(aXcptInfo, 5))
                oFile.write('\n\n')

            oFile.write(' D e b u g   I n f o\n')
            oFile.write('=====================\n\n')
            self._fHtmlDebugOutput = False
            self.debugDumpStuff(oFile.write)

            oFile.close()
        except:
            fRc = False

        self._fHtmlDebugOutput = fSaved
        return fRc
Beispiel #12
0
def show_error_web(exc_info):
    try:
        html = cgitb.html(exc_info)
        with NamedTemporaryFile(delete=False, mode='w',
                                suffix='.html') as tmp_file:
            tmp_file.write(html)
            webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
    except BaseException:
        # Oof. This happens sometimes with some exceptions ("AttributeError: characters_written").
        try:
            html = cgitb.text(exc_info)
            with NamedTemporaryFile(delete=False, mode='w',
                                    suffix='.txt') as tmp_file:
                tmp_file.write(html)
                webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
        except BaseException:
            # Hm... now it's getting ridiculous.
            try:
                html = ''.join(traceback.format_exception(*exc_info))
                with NamedTemporaryFile(delete=False, mode='w',
                                        suffix='.txt') as tmp_file:
                    tmp_file.write(html)
                    webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
            except BaseException:
                # Yikes!
                md = SkyTempleMessageDialog(
                    None,
                    Gtk.DialogFlags.DESTROY_WITH_PARENT,
                    Gtk.MessageType.ERROR,
                    Gtk.ButtonsType.OK,
                    _("Trying to display the error failed. Wow!"),
                    title=":(")
                md.run()
                md.destroy()
Beispiel #13
0
def top_level_exception(einfo=None):
    """Zpracuj aktuálně vyvolanou výjimku aplikace."""
    global _in_top_level_exception
    if not _in_top_level_exception:
        _in_top_level_exception = True
        try:
            if not einfo:
                einfo = sys.exc_info()
            if issubclass(einfo[0], SystemExit):
                sys.exit()
            tbstring = format_traceback()
            import cgitb
            try:
                tbstring = cgitb.text(einfo)
            except Exception:
                import traceback
                tbstring = "\n".join(traceback.format_exception(*einfo))
            log(OPERATIONAL, 'Top-level exception caught', tbstring)
            if pytis.form.run_dialog(pytis.form.BugReport, einfo):
                sys.exit()
            if pytis.config.debug_on_error:
                import pdb
                pdb.post_mortem(sys.exc_info()[2])
        finally:
            _in_top_level_exception = False
def exceptionHandler( *args ):
	'''
	This is a generic exception handler that can replace the default python exception handler if
	needed (ie: sys.excepthook=exceptionHandler).  It will mail
	'''
	try:
		eType, e, tb = args
	except TypeError:
		eType, e, tb = sys.exc_info()

	printMsg( '### ERROR - Python Unhandled Exception' )
	printMsg( '### ', eType.__name__, e )

	#
	toolName = findMostRecentDefitionOf( 'TOOL_NAME' ) or '<NO_TOOL>'

	#generate the message
	env = os.environ
	message = 'Subject: [ERROR] %s\n\n%s\n\n%s\n\n%s' % (toolName, cgitb.text( args ), '\n'.join( sys.path ),'\n'.join( [ '%s=%s' % (k, env[ k ]) for k in sorted( env.keys() ) ] ))

	#try to write a log
	fLog = open( 'c:/python_tool_log_%s.txt' % toolName, 'w' )
	try: fLog.write( message )
	except: pass
	finally: fLog.close()

	#try to mail a callstack
	try:
		import smtplib

		author = findMostRecentDefitionOf( '__author__' ) or DEFAULT_AUTHOR
		svr = smtplib.SMTP( 'exchange2' )
		svr.sendmail(os.environ[ 'USERNAME' ], [author, os.environ[ 'USERNAME' ]], message)
	except Exception, x:
		printMsg( 'ERROR: failed to mail exception dump', x )
    def handle_error():
        etype, evalue, etb = sys.exc_info()
        eclass = str if isinstance(etype, basestring) else etype
        if issubclass(eclass, KeyboardInterrupt): raise
        if issubclass(eclass, StopIteration): raise # let it propagate
        if issubclass(eclass, GeneratorExit): raise # let the generator die
        if issubclass(eclass, FilingFormatNotDocumented):
            # We don't bother to log these; we know they happen.
            return

        pathname = cover_record.get('pathname')
        report_id = cover_record.get('this_report_id')

        logdir = os.path.join(destdir, 'errors')
        if not os.path.exists(logdir): os.makedirs(logdir)
        fd, path = tempfile.mkstemp(dir=logdir, suffix = '.' + eclass.__name__)
        fo = os.fdopen(fd, 'w')
        lines_of_context = 5
        fo.write('Surprise; last filing successfully opened was\n%s in %s\n\n' %
                 (report_id, pathname))
        fo.write(cgitb.text((etype, evalue, etb), lines_of_context))
        fo.close()

        sys.stderr.write("logged error (in %s?) to %s, continuing\n" %
                         (report_id, path))
Beispiel #16
0
 def test_text(self):
     try:
         raise ValueError("Hello World")
     except ValueError as err:
         text = cgitb.text(sys.exc_info())
         self.assertIn("ValueError", text)
         self.assertIn("Hello World", text)
Beispiel #17
0
		def exceptionCallback(eType, eValue, eTraceBack):
				import cgitb

				txt = cgitb.text((eType, eValue, eTraceBack))


				logging.fatal(txt)
    def errorLog(self, sError, aXcptInfo, sLogFile):
        """
        Writes the error to a log file.
        """
        # Easy solution for log file size: Only one report.
        try:    os.unlink(sLogFile);
        except: pass;

        # Try write the log file.
        fRc    = True;
        fSaved = self._fHtmlDebugOutput;

        try:
            oFile = open(sLogFile, 'w');
            oFile.write(sError + '\n\n');
            if aXcptInfo[0] is not None:
                oFile.write(' B a c k t r a c e\n');
                oFile.write('===================\n');
                oFile.write(cgitb.text(aXcptInfo, 5));
                oFile.write('\n\n');

            oFile.write(' D e b u g   I n f o\n');
            oFile.write('=====================\n\n');
            self._fHtmlDebugOutput = False;
            self.debugDumpStuff(oFile.write);

            oFile.close();
        except:
            fRc = False;

        self._fHtmlDebugOutput = fSaved;
        return fRc;
Beispiel #19
0
def catch_and_mail_exception(func, msg):
    try:
        func()
    except:
        body = msg + '\n\n' + cgitb.text(sys.exc_info())

        error_mail( '*****@*****.**', ['*****@*****.**'], \
            'Open Library script exception', body)
Beispiel #20
0
def catch_and_mail_exception(func, msg):
    try:
        func()
    except:
        body = msg + '\n\n' + cgitb.text(sys.exc_info())

        error_mail( '*****@*****.**', ['*****@*****.**'], \
            'Open Library script exception', body)
Beispiel #21
0
def get_trance_back_msg():
    try:
        txt = cgitb.text(sys.exc_info(), context=12)
    except Exception as e2:
        logger.error(f"cgitb.text Exception:\n{e2}")
        txt = traceback.format_exc()
    logger.error(f"ERROR occur:\n{txt}")
    return txt
Beispiel #22
0
    def errorPage(self, sError, aXcptInfo, sLogFile = None):
        """
        Displays a page with an error message.
        """
        if sLogFile is not None:
            self.errorLog(sError, aXcptInfo, sLogFile);

        # Reset buffering, hoping that nothing was flushed yet.
        self._sBodyType = None;
        self._sHtmlBody = '';
        self._cchCached = 0;
        if not self._fHeaderWrittenOut:
            if self._fHtmlDebugOutput:
                self.setHeaderField('Content-Type', 'text/html; charset=utf-8');
            else:
                self.setHeaderField('Content-Type', 'text/plain; charset=utf-8');

        # Write the error page.
        if self._fHtmlDebugOutput:
            self.write('<html><head><title>Test Manage Error</title></head>\n' +
                       '<body><h1>Test Manager Error:</h1>\n' +
                       '<p>' + sError + '</p>\n');
        else:
            self.write(' Test Manage Error\n'
                       '===================\n'
                       '\n'
                       '' + sError + '\n\n');

        if aXcptInfo[0] is not None:
            if self._fHtmlDebugOutput:
                self.write('<h1>Backtrace:</h1>\n');
                self.write(cgitb.html(aXcptInfo, 5));
            else:
                self.write('Backtrace\n'
                           '---------\n'
                           '\n');
                self.write(cgitb.text(aXcptInfo, 5));
                self.write('\n\n');

        if self.kfDebugInfoEnabled:
            if self._fHtmlDebugOutput:
                self.write('<h1>Debug Info:</h1>\n');
            else:
                self.write('Debug Info\n'
                           '----------\n'
                           '\n');
            self.debugDumpStuff();

            for fn in self._afnDebugInfo:
                try:
                    fn(self, self._fHtmlDebugOutput);
                except Exception as oXcpt:
                    self.write('\nDebug info callback %s raised exception: %s\n' % (fn, oXcpt));

        if self._fHtmlDebugOutput:
            self.write('</body></html>');

        self.flush();
    def errorPage(self, sError, aXcptInfo, sLogFile = None):
        """
        Displays a page with an error message.
        """
        if sLogFile is not None:
            self.errorLog(sError, aXcptInfo, sLogFile);

        # Reset buffering, hoping that nothing was flushed yet.
        self._sBodyType = None;
        self._sHtmlBody = '';
        self._cchCached = 0;
        if not self._fHeaderWrittenOut:
            if self._fHtmlDebugOutput:
                self.setHeaderField('Content-Type', 'text/html; charset=utf-8');
            else:
                self.setHeaderField('Content-Type', 'text/plain; charset=utf-8');

        # Write the error page.
        if self._fHtmlDebugOutput:
            self.write('<html><head><title>Test Manage Error</title></head>\n' +
                       '<body><h1>Test Manager Error:</h1>\n' +
                       '<p>' + sError + '</p>\n');
        else:
            self.write(' Test Manage Error\n'
                       '===================\n'
                       '\n'
                       '' + sError + '\n\n');

        if aXcptInfo[0] is not None:
            if self._fHtmlDebugOutput:
                self.write('<h1>Backtrace:</h1>\n');
                self.write(cgitb.html(aXcptInfo, 5));
            else:
                self.write('Backtrace\n'
                           '---------\n'
                           '\n');
                self.write(cgitb.text(aXcptInfo, 5));
                self.write('\n\n');

        if self.kfDebugInfoEnabled:
            if self._fHtmlDebugOutput:
                self.write('<h1>Debug Info:</h1>\n');
            else:
                self.write('Debug Info\n'
                           '----------\n'
                           '\n');
            self.debugDumpStuff();

            for fn in self._afnDebugInfo:
                try:
                    fn(self, self._fHtmlDebugOutput);
                except Exception as oXcpt:
                    self.write('\nDebug info callback %s raised exception: %s\n' % (fn, oXcpt));

        if self._fHtmlDebugOutput:
            self.write('</body></html>');

        self.flush();
Beispiel #24
0
        def internal_error(error):
            message = Message(_('[PythonFOSDEM] Error 500'),
                              sender='*****@*****.**',
                              recipients=['*****@*****.**'])
            message.body = render_template('emails/send_error_500.txt',
                                           error=cgitb.text(sys.exc_info()))

            mail.send(message)
            return render_template('errors/500.html'), 500
Beispiel #25
0
 def tick(self):
     """Go through one tick."""
     doing = self.doing
     self.doing = []
     for cmd in doing:
         try:
             cmd()
         except:
             logging.error(cgitb.text(sys.exc_info()))
Beispiel #26
0
 def tick(self):
     """Go through one tick."""
     doing = self.doing
     self.doing = []
     for cmd in doing:
         try:
             cmd()
         except:
             logging.error(cgitb.text(sys.exc_info()))
Beispiel #27
0
def exception_hook(*exc_info):
    if exc_info == ():
        exc_info = sys.exc_info()
    fp = file('%s-error' % debuglogfile, 'a')
    fp.write(cgitb.text(exc_info))
    fp.close()
    logger.critical('ERROR EXIT -- see %s-error for detailed traceback' % debuglogfile)
    for tbline in traceback.format_exc().splitlines():
        logger.debug('%s', tbline)
Beispiel #28
0
def exception_hook(*exc_info):
    if exc_info == ():
        exc_info = sys.exc_info()
    fp = file('%s-error' % debuglogfile, 'a')
    fp.write(cgitb.text(exc_info))
    fp.close()
    logger.critical('ERROR EXIT -- see %s-error for detailed traceback' %
                    debuglogfile)
    for tbline in traceback.format_exc().splitlines():
        logger.debug('%s', tbline)
        def internal_error(error):
            message = Message(
                _("[PythonFOSDEM] Error 500"),
                sender="*****@*****.**",
                recipients=["*****@*****.**"],
            )
            message.body = render_template("emails/send_error_500.txt", error=cgitb.text(sys.exc_info()))

            mail.send(message)
            return render_template("errors/500.html"), 500
Beispiel #30
0
 def _exc_info_to_string(self, err, test):
     """Converts a sys.exc_info()-style tuple of values into a string."""
     exctype, value, tb = err
     # Skip test runner traceback levels
     while tb and self._is_relevant_tb_level(tb):
         tb = tb.tb_next
         if exctype is test.failureException:
             # Skip assert*() traceback levels
             length = self._count_relevant_tb_levels(tb)
             return ''.join(traceback.format_exception(exctype, value, tb, length))
     return cgitb.text((exctype, value, tb))
Beispiel #31
0
 def __init__(self, exc_type, exc_obj, exc_tb, title=None):
     QDialog.__init__(self)
     self.ui = Ui_ExceptHookDialog()
     self.ui.setupUi(self)
     if title:
         self.setWindowTitle(self.windowTitle() + ": " + title)
     msg = "%s: %s" % (exc_type.__name__, exc_obj)
     self.ui.exceptionLabel.setText(msg)
     html = cgitb.text((exc_type, exc_obj, exc_tb))
     self.ui.tracebackBrowser.setText(html)
     self.resize(650, 350)  # give enough space to see the backtrace better
Beispiel #32
0
 def __init__(self, etype, evalue, etb):
     gtk.MessageDialog.__init__(self, buttons=gtk.BUTTONS_CLOSE, type=gtk.MESSAGE_ERROR)
     self.set_resizable(True)
     self.set_markup(_("An error has occured:\n%r\nYou should save your work and restart the application. If the error occurs again please report it to the developer." % evalue))
     import cgitb
     text = cgitb.text((etype, evalue, etb), 5)
     expander = gtk.Expander(_("Exception Details"))
     self.vbox.pack_start(expander)
     textview = gtk.TextView()
     textview.get_buffer().set_text(text)
     expander.add(scrolled(textview))
     self.show_all()
Beispiel #33
0
def _do_verbose_exception(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()

    txt = cgitb.text(exc_info)

    d = dt.datetime.now()
    p = (d.year, d.month, d.day, d.hour, d.minute, d.second)        
    filename = "ErrorDump-%d%02d%02d-%02d%02d%02d.txt" % p

    open(filename,'w').write(txt)
    print "** EXITING on unhandled exception - See %s" % filename  
    sys.exit(1)
Beispiel #34
0
def do_verbose_exception(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()

    txt = cgitb.text(exc_info)

    d = datetime.now()
    p = (d.year, d.month, d.day, d.hour, d.minute, d.second)
    filename = "errors/ErrorDump-%d%02d%02d-%02d%02d%02d.txt" % p

    open(filename, 'w').write(txt)
    print "** EXITING on unhandled exception - See %s" % filename
    sys.exit(1)
Beispiel #35
0
def text_traceback() -> str:
    info = sys.exc_info()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        try:
            text = cgitb.text(info)
        except RuntimeError:
            # there is werkzeug.local.LocalProxy object inside traceback, that
            # cannot be printed out by the cgitb
            res = "".join(traceback.format_tb(info[-1]))
        else:
            res = 'the original traceback:'.join(
                text.split('the original traceback:')[1:]).strip()

    return res
Beispiel #36
0
 def handle(cls, e: Exception):
     cls.log_dir = get_log_dir()
     print('Error: ', e)
     try:
         txt = cgitb.text(sys.exc_info(), context=12)  # fixme: 可能出错?
     except Exception as e2:
         print('cgitb.text Exception')
         print(e2)
         txt = traceback.format_exc()
     Path(cls.log_dir).mkdir(parents=True, exist_ok=True)
     file_name = datetime.datetime.now().strftime(
         '%Y-%m-%d_%H:%M:%S_%f') + '.log'
     log_file = Path(cls.log_dir) / file_name
     log_file.write_text(txt)
     print(str(log_file))
Beispiel #37
0
def main():
    """
    Receive the email via the stdin and send it to the OpenERP Server
    """

    parser = configure_parser()
    (options, args) = parser.parse_args()
    method = "message_process"
    email_parser = EmailParser(options.userid,
                               options.password,
                               options.dbname,
                               options.host,
                               options.port,
                               model=options.model,
                               email_default=options.default)
    msg_txt = sys.stdin.read()
    custom_values = {}
    if not options.model:
        method = "message_catchall"
    try:
        custom_values = dict(eval(options.custom_values or "{}"))
    except:
        import traceback
        traceback.print_exc()

    try:
        email_parser.parse(method, msg_txt, custom_values,
                           options.save_original or False)
    except Exception:
        msg = '\n'.join([
            'parameters',
            '==========',
            '%r' % (options, ),
            'traceback',
            '=========',
            '%s' % (cgitb.text(sys.exc_info())),
        ])

        subject = '[OPENERP]:ERROR: Mailgateway - %s' % time.strftime(
            '%Y-%m-%d %H:%M:%S')
        send_mail(config.MAIL_ERROR,
                  config.MAIL_ADMINS,
                  subject,
                  msg,
                  files=[('message.txt', msg_txt)])
        sys.stderr.write(
            "Failed to deliver email to OpenERP Server, sending error notification to %s\n"
            % config.MAIL_ADMINS)
Beispiel #38
0
def exception_to_text(exc_info=None):
	"Return current exception as text, or '' if no current exception."
	if exc_info is None:
		exc_info = sys.exc_info()
	
	if exc_info[0] is None:
		return '' # no current exception
		
	if hasattr(cgitb, 'text'):
		txt = cgitb.text(exc_info)
	else:
		# eariler Pythons lack .text() ...
		# this will be ugly, but its the best I can safely do
		txt = cgitb.html(exc_info)

	return txt
Beispiel #39
0
def exception_to_text(exc_info=None):
    "Return current exception as text, or '' if no current exception."
    if exc_info is None:
        exc_info = sys.exc_info()

    if exc_info[0] is None:
        return ''  # no current exception

    if hasattr(cgitb, 'text'):
        txt = cgitb.text(exc_info)
    else:
        # eariler Pythons lack .text() ...
        # this will be ugly, but its the best I can safely do
        txt = cgitb.html(exc_info)

    return txt
Beispiel #40
0
    def get_pretty_errors(exc):
        import traceback

        try:
            text = cgitb.text(exc)
            html = cgitb.html(exc)
        except:
            # errors might be thrown when cgitb tries to inspect stuff,
            # in which case just get a regular stacktrace
            from cherrypy._cperror import format_exc
            text = format_exc(exc)
            html = None

        name = traceback.format_exception(*exc)[-1]

        return name, text, html
Beispiel #41
0
def test(Mode=0):
    if Mode == 0:
        func(1, 0)
    elif Mode == 1:
        try:
            func(1, 0)
        except:
            info = sys.exc_info()
            print('4.info=', cgitb.text(info))
    elif Mode == 2:
        cgitb.handler()
        func(1, 0)
    elif Mode == 3:
        cgitb.enable(display=0, logdir='./cgi_log', context=5, format='text')
        cgitb.handler()
        func(1, 0)
Beispiel #42
0
def _format_exc_stack_trace_with_vars(_, __, event_dict):
    exc_info = event_dict.get("exc_info", None)
    if exc_info:
        if sys.version_info[0] >= 3 and isinstance(exc_info, BaseException):
            exc_info = (exc_info.__class__, exc_info, exc_info.__traceback__)
        elif isinstance(exc_info, tuple):
            pass
        elif exc_info:
            exc_info = sys.exc_info()
        try:
            match = _frames_regex.search(cgitb.text(exc_info))
            event_dict["stack_trace_with_vars"] = match[1]
        except Exception as e:
            event_dict[
                "stack_trace_with_vars"] = "Collection failure: {}".format(e)
    return event_dict
Beispiel #43
0
 def __init__(self, exc_type, exc_value, tb, text=None):
     if text is None:
         text = _('An error occurred.')
     gtk.MessageDialog.__init__(self, buttons=gtk.BUTTONS_CLOSE,
                                type=gtk.MESSAGE_ERROR,
                                message_format=text)
     self.set_resizable(True)
     import cgitb
     text = cgitb.text((exc_type, exc_value, tb), 5)
     expander = gtk.Expander(_('Exception details'))
     self.vbox.pack_start(expander)
     textview = gtk.TextView()
     textview.get_buffer().set_text(text)
     scrolled_window = gtk.ScrolledWindow()
     scrolled_window.add(textview)
     expander.add(scrolled_window)
     self.show_all()
Beispiel #44
0
async def exception_middleware(request, handler):
    try:
        return await handler(request)
    except Exception as err:
        import cgitb
        context = 10
        if "/api" in request.path:
            return web.json_response({
                "ERROR":
                str(err),
                "tb":
                cgitb.text(sys.exc_info(), context=context)
            })
        else:
            return web.Response(text=cgitb.html(sys.exc_info(),
                                                context=context),
                                content_type='text/html')
Beispiel #45
0
    def wrapper(self, *args, **kwargs):
        try:
            return method(self, *args, **kwargs)
        except HTTPError as e:
            logger.debug(e.log_message)
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps({"message": e.log_message}, indent=2, cls=self.Encoder))
            self.set_status(e.status_code)
            self.finish()
        except Exception as e:
            logger.debug("Caught exception")
            logger.exception(cgitb.text(sys.exc_info()))

            self.set_header("Content-Type", "application/json")
            self.write(json.dumps({"message": "Internal server error"}))
            self.set_status(500)
            self.finish()
Beispiel #46
0
 def __init__(self, exc_type, exc_value, tb, text=None):
     if text is None:
         text = _('An error occurred.')
     gtk.MessageDialog.__init__(self, buttons=gtk.BUTTONS_CLOSE,
                                type=gtk.MESSAGE_ERROR,
                                message_format=text)
     self.set_resizable(True)
     import cgitb
     text = cgitb.text((exc_type, exc_value, tb), 5)
     expander = gtk.Expander(_('Exception details'))
     self.vbox.pack_start(expander)
     textview = gtk.TextView()
     textview.get_buffer().set_text(text)
     scrolled_window = gtk.ScrolledWindow()
     scrolled_window.add(textview)
     expander.add(scrolled_window)
     self.show_all()
Beispiel #47
0
def excepthook(etype, value, tb):
    # Added this line for debugging why https://travis-ci.org/cubing/tnoodle/builds/15966902
    # hit pdb instead of just printing a traceback and exiting.
    # Once that problem is solved, we can delete this code.
    print("Hit excepthook! stderr.isatty: %s stdin.isatty: %s stdout.isatty: %s" % (sys.stderr.isatty(), sys.stdin.isatty(), sys.stdout.isatty()))

    # Workaround for isatty weirdness mentioned above.
    isTravisCiBuild = os.environ.get('TRAVIS_BRANCH', None)
    if not sys.stdout.isatty() or not sys.stderr.isatty() or not sys.stdin.isatty() or isTravisCiBuild:
        # stdin, stdout, or stderr is redirected, so don't enter pdb
        sys.stderr.write(cgitb.text((etype, value, tb)))
    else:
        if tb:
            traceback.print_exception(etype, value, tb)
        if Throwable and issubclass(etype, Throwable):
            value.printStackTrace()
        pdb.post_mortem(tb)
Beispiel #48
0
def run(argv):
    try:
        opt, args = getoptions(argv)
    except getopt.GetoptError:
        usage(argv)
    try:
        main(sys.argv, opt, args)
    except KeyboardInterrupt:
        raise
    except SystemExit:
        raise
    except lcg.ProcessingError as p:
        # Handles errors due to wrong format of input file. Gives the reason for the error and
        # clues to find it in form of name of the defective file and some section of text in which
        # the error is located.
        sys.stderr.write(
            lcg_exception_details("PARSING ERROR (error in source text)",
                                  p.info(), p.reason()))
        sys.exit(1)
    except Exception as ex:
        if opt['plain']:
            raise
        einfo = sys.exc_info()
        try:
            import cgitb
            sys.stderr.write(cgitb.text(einfo))
        except Exception as e:
            sys.stderr.write("Unable to generate detailed traceback: " +
                             unistr(e) + "\n")
            import traceback
            traceback.print_exception(*einfo)
        # The _lcg_processing_details exception attribute should not be generally used to pass data
        # about errors in input. It is much prefered that you raise a proper ProcessingError
        # exception whenever the error can be clearly identified as an error in input. The bellow
        # exception attribute can serve 1) to better debug programming errors by giving pointers to
        # which piece of input it triggered and 2) to find errors in input which are not caught
        # right away and cause errors in program code at a different place.
        if hasattr(ex, '_lcg_processing_details'):
            sys.stderr.write(
                lcg_exception_details("LCG exception details",
                                      ex._lcg_processing_details, unistr(ex)))
        if _debug:
            import pdb
            pdb.post_mortem(sys.exc_info()[2])
        sys.exit(1)
def main():
    """
    Receive the email via the stdin and send it to the OpenERP Server
    """
    parser = configure_parser()
    (options, args) = parser.parse_args()


    email_parser = EmailParser(options.userid,
                               options.password,
                               options.model,
                               options.default,
                               dbname=options.dbname,
                               host=options.host,
                               port=options.port)


    msg_txt = sys.stdin.read()

    custom_values = {}
    try:
        custom_values = dict(eval(options.custom_values or {} ))
    except:
        import traceback
        traceback.print_exc()

    try:
        email_parser.parse(msg_txt, custom_values, options.save_original or False)
    except Exception:
        msg = '\n'.join([
            'parameters',
            '==========',
            '%r' % (options,),
            'traceback',
            '=========',
            '%s' % (cgitb.text(sys.exc_info())),
        ])

        subject = '[OPENERP]:ERROR: Mailgateway - %s' % time.strftime('%Y-%m-%d %H:%M:%S')
        send_mail(
            config.MAIL_ERROR,
            config.MAIL_ADMINS,
            subject, msg, files=[('message.txt', msg_txt)]
        )
        sys.stderr.write("Failed to deliver email to OpenERP Server, sending error notification to %s\n" % config.MAIL_ADMINS)
Beispiel #50
0
def run(func, *args, **kwargs):
    conf = res.conf
    
    if conf.get("cgi", {}).get("errors_on_screen", False):
        cgitb.enable()
        return func(*args, **kwargs)
    
    try:
        return func(*args, **kwargs)        
    except Exception, e:
        
        # Send traceback in an email to conf.cgi.error_waters
        import emailer
        system_name = conf.get("system", {}).get("name", "Undefined")
        if 'REMOTE_USER' in os.environ:
            system_name = '%s: %s' % (system_name, os.environ['REMOTE_USER'])
        email = conf.get("cgi", {}).get("error_watchers",
                                        ["*****@*****.**"])
        filename = os.path.basename(sys.argv[0])
        emailer.emailer(emailTo=email,
                        emailFrom='*****@*****.**',
                        emailSubject='PLANT_ERROR: %s: %s: %s' % \
                           (system_name, filename, str(e)[:40]),
                        emailHtml=cgitb.html(sys.exc_info()),
                        emailText=cgitb.text(sys.exc_info()))

        # display message to user.
        logo = "<img src='images/mypub_logo.jpg'/>"
        button = '<a href="javascript:back()">GO BACK</a>'
        msg = markup('''
        An Unexpected Error Occurred: !%s!
        Details have been sent to %s

        ''' % (e, email))
        error_page = """
        <table style='border: 0' width='100%%' border='0'>
          <tr>
             <td style='border: 0;' width='30px' valign='top'>%s</td>
             <td style='border: 0;'>%s</td>
          </tr>
        </table>""" % (logo, msg) + button
        return HTML(msg=error_page)
Beispiel #51
0
def run(argv):
    try:
        opt, args = getoptions(argv)
    except getopt.GetoptError:
        usage(argv)
    try:
        main(sys.argv, opt, args)
    except KeyboardInterrupt:
        raise
    except SystemExit:
        raise
    except lcg.ProcessingError as p:
        # Handles errors due to wrong format of input file. Gives the reason for the error and
        # clues to find it in form of name of the defective file and some section of text in which
        # the error is located.
        sys.stderr.write(lcg_exception_details("PARSING ERROR (error in source text)",
                                               p.info(), p.reason()))
        sys.exit(1)
    except Exception as ex:
        if opt['plain']:
            raise
        einfo = sys.exc_info()
        try:
            import cgitb
            sys.stderr.write(cgitb.text(einfo))
        except Exception as e:
            sys.stderr.write("Unable to generate detailed traceback: " + str(e) + "\n")
            import traceback
            traceback.print_exception(*einfo)
        # The _lcg_processing_details exception attribute should not be generally used to pass data
        # about errors in input. It is much prefered that you raise a proper ProcessingError
        # exception whenever the error can be clearly identified as an error in input. The bellow
        # exception attribute can serve 1) to better debug programming errors by giving pointers to
        # which piece of input it triggered and 2) to find errors in input which are not caught
        # right away and cause errors in program code at a different place.
        if hasattr(ex, '_lcg_processing_details'):
            sys.stderr.write(lcg_exception_details("LCG exception details",
                                                   ex._lcg_processing_details, str(ex)))
        if _debug:
            import pdb
            pdb.post_mortem(sys.exc_info()[2])
        sys.exit(1)
Beispiel #52
0
def event_flusher():
    #the current batch of events is over, so flush anything out. This largely
    #involves sending prompts and such.
    try:
        for obj in MUDObject._instances:
            obj.eventFlush()
    finally:
        try:
            grailmud.instance.ticker.add_command(flusher)
        except BaseException, e:
            logging.error("event_flusher experienced an error re-adding itself"
                          " to the commands queue. Stopping the reactor.")
            logging.error("If there was an error in an eventFlush call and we "
                          "get here and reraise, the previous error poofs, "
                          "but if we don't reraise here, our error poofs. "
                          "Compromise: write our error to the log and don't "
                          "reraise.")
            import sys, cgitb
            logging.error(cgitb.text(sys.exc_info()))
            reactor.stop()
Beispiel #53
0
def excepthook(etype, value, tb):
    # Added this line for debugging why https://travis-ci.org/cubing/tnoodle/builds/15966902
    # hit pdb instead of just printing a traceback and exiting.
    # Once that problem is solved, we can delete this code.
    print(
        "Hit excepthook! stderr.isatty: %s stdin.isatty: %s stdout.isatty: %s"
        % (sys.stderr.isatty(), sys.stdin.isatty(), sys.stdout.isatty()))

    # Workaround for isatty weirdness mentioned above.
    isTravisCiBuild = os.environ.get('TRAVIS_BRANCH', None)
    if not sys.stdout.isatty() or not sys.stderr.isatty(
    ) or not sys.stdin.isatty() or isTravisCiBuild:
        # stdin, stdout, or stderr is redirected, so don't enter pdb
        sys.stderr.write(cgitb.text((etype, value, tb)))
    else:
        if tb:
            traceback.print_exception(etype, value, tb)
        if Throwable and issubclass(etype, Throwable):
            value.printStackTrace()
        pdb.post_mortem(tb)
Beispiel #54
0
def event_flusher():
    #the current batch of events is over, so flush anything out. This largely
    #involves sending prompts and such.
    try:
        for obj in MUDObject._instances:
            obj.eventFlush()
    finally:
        try:
            grailmud.instance.ticker.add_command(flusher)
        except BaseException, e:
            logging.error("event_flusher experienced an error re-adding itself"
                          " to the commands queue. Stopping the reactor.")
            logging.error("If there was an error in an eventFlush call and we "
                          "get here and reraise, the previous error poofs, "
                          "but if we don't reraise here, our error poofs. "
                          "Compromise: write our error to the log and don't "
                          "reraise.")
            import sys, cgitb
            logging.error(cgitb.text(sys.exc_info()))
            reactor.stop()
def exceptionHandler(*args):
    '''
	This is a generic exception handler that can replace the default python exception handler if
	needed (ie: sys.excepthook=exceptionHandler).  It will mail
	'''
    try:
        eType, e, tb = args
    except TypeError:
        eType, e, tb = sys.exc_info()

    printMsg('### ERROR - Python Unhandled Exception')
    printMsg('### ', eType.__name__, e)

    #
    toolName = findMostRecentDefitionOf('TOOL_NAME') or '<NO_TOOL>'

    #generate the message
    env = os.environ
    message = 'Subject: [ERROR] %s\n\n%s\n\n%s\n\n%s' % (
        toolName, cgitb.text(args), '\n'.join(sys.path), '\n'.join(
            ['%s=%s' % (k, env[k]) for k in sorted(env.keys())]))

    #try to write a log
    fLog = open('c:/python_tool_log_%s.txt' % toolName, 'w')
    try:
        fLog.write(message)
    except:
        pass
    finally:
        fLog.close()

    #try to mail a callstack
    try:
        import smtplib

        author = findMostRecentDefitionOf('__author__') or DEFAULT_AUTHOR
        svr = smtplib.SMTP('exchange2')
        svr.sendmail(os.environ['USERNAME'], [author, os.environ['USERNAME']],
                     message)
    except Exception, x:
        printMsg('ERROR: failed to mail exception dump', x)
Beispiel #56
0
def excepthook(etype, value, tb):
    # Added this line for debugging why https://travis-ci.org/cubing/tnoodle/builds/15966902
    # hit pdb instead of just printing a traceback and exiting.
    # Once that problem is solved, we can delete this code.
    print("Hit excepthook! stderr.isatty: %s stdin.isatty: %s stdout.isatty: %s" % (sys.stderr.isatty(), sys.stdin.isatty(), sys.stdout.isatty()))

    # Workaround for isatty weirdness mentioned above.
    isTravisCiBuild = os.environ.get('TRAVIS_BRANCH', None)
    if not sys.stdout.isatty() or not sys.stderr.isatty() or not sys.stdin.isatty() or isTravisCiBuild:
        # We're not running interactively, so don't enter PDB.
        sys.stderr.write(cgitb.text((etype, value, tb)))

        while tb.tb_next:
            tb = tb.tb_next
        sys.stderr.write("Globals: {}\n".format(tb.tb_frame.f_locals))
        sys.stderr.write("Locals: {}\n".format(tb.tb_frame.f_locals))
    else:
        if tb:
            traceback.print_exception(etype, value, tb)
        if Throwable and issubclass(etype, Throwable):
            value.printStackTrace()
        pdb.post_mortem(tb)
Beispiel #57
0
        def wrapped_func(*args, **kwargs):
            txt = func.__name__ + '('
            txt_args = ", ".join([_conv_arg_to_txt(a) for a in args])
            txt_kwargs = ", ".join(['%s=%s' % (str(k), _conv_arg_to_txt(v)) for k, v in kwargs.items()])
            if txt_args:
                txt += txt_args
                if txt_kwargs:
                    txt += ', '
            if txt_kwargs:
                txt += txt_kwargs
            txt += ')\n'

            fout = os.path.join(world.cfg["test_result_dir"], 'test-steps.txt')
            with open(fout, 'a') as f:
                f.write(txt)

            try:
                return func(*args, **kwargs)
            except:
                txt = cgitb.text(sys.exc_info())
                with open(fout, 'a') as f:
                    f.write(txt)
                raise
Beispiel #58
0
        def wrapped_func(*args, **kwargs):
            txt = func.__name__ + '('
            txt_args = ", ".join([_conv_arg_to_txt(a) for a in args])
            txt_kwargs = ", ".join(['%s=%s' % (str(k), _conv_arg_to_txt(v)) for k, v in kwargs.items()])
            if txt_args:
                txt += txt_args
                if txt_kwargs:
                    txt += ', '
            if txt_kwargs:
                txt += txt_kwargs
            txt += ')\n'

            fout = os.path.join(world.cfg["dir_name"], 'test-steps.txt')
            with open(fout, 'a') as f:
                f.write(txt)

            try:
                return func(*args, **kwargs)
            except:
                txt = cgitb.text(sys.exc_info())
                with open(fout, 'a') as f:
                    f.write(txt)
                raise
def exceptionHandler(*args):
    '''
	This is a generic exception handler that can replace the default python exception handler if
	needed (ie: sys.excepthook=exceptionHandler).  It will mail
	'''
    try:
        eType, e, tb = args
    except TypeError:
        eType, e, tb = sys.exc_info()

    printMsg('### ERROR - Python Unhandled Exception')
    printMsg('### ', eType.__name__, e)

    #try to mail a callstack
    try:
        import smtplib
        message = 'Subject: [ERROR] assetEditor\n\n%s' % cgitb.text(args)

        author = findMostRecentDefitionOf('__author__') or DEFAULT_AUTHOR
        svr = smtplib.SMTP('exchange2')
        svr.sendmail(os.environ['USERNAME'], [author, os.environ['USERNAME']],
                     message)
    except Exception, x:
        printMsg('ERROR: failed to mail exception dump', x)