我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用traceback.format_exception()。
def on_command_error(self, error, ctx): ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure, commands.CommandNotFound, commands.UserInputError, discord.HTTPException) error = getattr(error, 'original', error) if isinstance(error, ignored): return if ctx.message.server: fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})' else: fmt = 'Channel: {0} (ID: {0.id})' exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False) description = '```py\n%s\n```' % ''.join(exc) time = datetime.datetime.utcnow() name = ctx.command.qualified_name author = '{0} (ID: {0.id})'.format(ctx.message.author) location = fmt.format(ctx.message.channel, ctx.message.server) message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description) self.bot.logs['discord'].critical(message)
def upload_output_xml(request): if request.method == 'POST': form = UploadOutputXmlForm(request.POST, request.FILES) print "HELLP" if form.is_valid(): print "YES" try: handle_uploaded_file(request) except: tt, value, tb = sys.exc_info() print {'exception_value': value, 'value': tt, 'tb': traceback.format_exception(tt, value, tb)} return handler500(request) return HttpResponseRedirect(reverse('home')) else: return handler500(request) else: print "No" form = UploadOutputXmlForm() return render(request, 'report/upload_xml_file.html', {'form': form})
def handler500(request, template_name='500.html'): t = get_template(template_name) tt, value, tb = sys.exc_info() ctx = Context({'exception_value': value, 'value': tt, 'tb': traceback.format_exception(tt, value, tb)}) return HttpResponseServerError(t.render(ctx))
def export_as_string(self): """ Returns a CQL query string that can be used to recreate the entire keyspace, including user-defined types and tables. """ cql = "\n\n".join([self.as_cql_query() + ';'] + self.user_type_strings() + [f.export_as_string() for f in self.functions.values()] + [a.export_as_string() for a in self.aggregates.values()] + [t.export_as_string() for t in self.tables.values()]) if self._exc_info: import traceback ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \ (self.name) for line in traceback.format_exception(*self._exc_info): ret += line ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql return ret return cql
def export_as_string(self): """ Returns a string of CQL queries that can be used to recreate this table along with all indexes on it. The returned string is formatted to be human readable. """ if self._exc_info: import traceback ret = "/*\nWarning: Table %s.%s is incomplete because of an error processing metadata.\n" % \ (self.keyspace_name, self.name) for line in traceback.format_exception(*self._exc_info): ret += line ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql() elif not self.is_cql_compatible: # If we can't produce this table with CQL, comment inline ret = "/*\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\n" % \ (self.keyspace_name, self.name) ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql() else: ret = self._all_as_cql() return ret
def error_response(func): @wraps(func) def wrapper(self, *args, **kwargs): try: result = func(self, *args, **kwargs) except Exception as ex: if not isinstance(ex, (web.HTTPError, ExecutionError, GraphQLError)): tb = ''.join(traceback.format_exception(*sys.exc_info())) app_log.error('Error: {0} {1}'.format(ex, tb)) self.set_status(error_status(ex)) error_json = json_encode({'errors': error_format(ex)}) app_log.debug('error_json: %s', error_json) self.write(error_json) else: return result return wrapper
def write_error(self, status_code, **kwargs): """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback self.set_header('Content-Type', 'text/plain') for line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish("<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % { "code": status_code, "message": self._reason, })
def write_error(self, status_code, **kwargs): self.set_header('Content-Type', 'text/json') if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback lines = [] for line in traceback.format_exception(*kwargs["exc_info"]): lines.append(line) self.finish(json.dumps({ 'code': status_code, 'status': self._reason, 'traceback': lines, 'results': {}, })) else: self.finish(json.dumps({ 'code': status_code, 'status': self._reason, 'results': {}, }))
def build_fault(cls, e, tb, include_traceback=False): """ Builds a L{ErrorFault<pyamf.remoting.ErrorFault>} object based on the last exception raised. If include_traceback is C{False} then the traceback will not be added to the L{remoting.ErrorFault}. """ if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ details = None if include_traceback: details = traceback.format_exception(cls, e, tb) return remoting.ErrorFault( code=code, description=unicode(e), details=details )
def safe_str(o): """safe_str(anything) -> string Returns a string representation of an object, or a string containing a traceback, if that object's __str__ raised an exception. """ try: return str(o) except: strExc = '\n'.join(traceback.format_exception(*sys.exc_info())) clsName = _determineClassName(o) obId = id(o) return '<%s instance at %s with str error %s>' % ( clsName, obId, strExc) ##the following were factored out of usage
def format_exception(exc_info, encoding='UTF-8'): ec, ev, tb = exc_info # Our exception object may have been turned into a string, and Python 3's # traceback.format_exception() doesn't take kindly to that (it expects an # actual exception object). So we work around it, by doing the work # ourselves if ev is not an exception object. if not is_base_exception(ev): tb_data = force_unicode( ''.join(traceback.format_tb(tb)), encoding) ev = exc_to_unicode(ev) return tb_data + ev else: return force_unicode( ''.join(traceback.format_exception(*exc_info)), encoding)
def write_error(self, status_code, **kwargs): """ Method gets traceback, writes it into response, finishes response. :param status_code: tornado parameter to format html, we don't use it. :type status_code: int :param kwargs: in debug mode must contain exc_info. :type kwargs: dict """ exc_info = kwargs.get('exc_info') if self.settings.get( "serve_traceback") and exc_info: # pragma: no cover # in debug mode, try to send a traceback self.set_header('Content-Type', 'text/plain') for line in traceback.format_exception(*exc_info): self.write(line) # exc_info[1] - HTTPError instance # Finish request with exception body or exception reason err_text = getattr(exc_info[1], 'body', self._reason) self.write(err_text) self.finish()
def sendResult(self, test, outcome, trace = None): if _channel is not None: tb = None message = None if trace is not None: traceback.print_exc() formatted = traceback.format_exception(*trace) # Remove the 'Traceback (most recent call last)' formatted = formatted[1:] tb = ''.join(formatted) message = str(trace[1]) _channel.send_event( name='result', outcome=outcome, traceback = tb, message = message, test = test.id() )
def excepthook( self, type_, value, tb ): # emergency write self.__session_log.write( 'excepthook called\n' ) self.__session_log.flush() all_exception_lines = traceback.format_exception( type_, value, tb ) for line in all_exception_lines: self.__session_log.write( line ) self.__session_log.flush() # cannot use the GUI window now app is not sane self.app.log.removeHandler( self.widget_log_handler ) self.app.log.error( 'excepthook called' ) for line in all_exception_lines: self.app.log.error( line.replace( '\n', '' ) ) self.app.runInForeground( self.app.log.addHandler, (self.widget_log_handler,) ) self.app.runInForeground( self.app.log.error, ('Check log for traceback details',) )
def _process_wrapper(function, upwards, profile, *args, **kwargs): """Wrap a process with additional features.""" try: if profile: _run_profiler(function, *args, **kwargs) else: function(*args, **kwargs) except Exception: process = multiprocessing.current_process() info = sys.exc_info() exception = traceback.format_exception( info[0], info[1], info[2].tb_next) _send_message(upwards, _MESSAGE_ERROR, process_id=process.pid, process_name=process.name, message=''.join(exception).rstrip()) finally: upwards.close()
def addFailure(self, test, err, systemout = '', systemerr = ''): """Add failure output to Xunit report. """ taken = self._timeTaken() tb = format_exception(err) self.stats['failures'] += 1 id = test.id() self.errorlist.append( '<testcase classname=%(cls)s name=%(name)s time="%(taken).3f">' '<failure type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>' '</failure><system-out>%(systemout)s</system-out><system-err>%(systemerr)s</system-err></testcase>' % {'cls': self._quoteattr(id_split(id)[0]), 'name': self._quoteattr(id_split(id)[-1]), 'taken': taken, 'errtype': self._quoteattr(nice_classname(err[0])), 'message': self._quoteattr(exc_message(err)), 'tb': escape_cdata(tb), 'systemout': systemout, 'systemerr': systemerr, })
def lambda_handler(data, context): """ Execution wrapper on AWS Lambda :param data: Inputs to the botengine :param context: Ignored :return: JSON structure with errors and debug information """ if data is None: return 0 logger = LambdaLogger() try: bot = importlib.import_module('bot') botengine._run(bot, data, logger) except: import traceback import sys (t, v, tb) = sys.exc_info() logger.tracebacks = traceback.format_exception(t, v, tb) return logger.get_lambda_return()
def __init__(self, test_name, exc_info): """Constructs a LinkerExceptionTestResult object. Args: test_name: name of the test which raised an exception. exc_info: exception info, ostensibly from sys.exc_info(). """ exc_type, exc_value, exc_traceback = exc_info trace_info = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)) log_msg = 'Exception:\n' + trace_info super(LinkerExceptionTestResult, self).__init__( test_name, base_test_result.ResultType.FAIL, log="%s %s" % (exc_type, log_msg))
def user_exception(self, frame, info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile or self._wait_for_breakpoint: return extype, exvalue, trace = info # pre-process stack trace as it isn't pickeable (cannot be sent pure) msg = ''.join(traceback.format_exception(extype, exvalue, trace)) # in python3.5, convert FrameSummary to tuples (py2.7+ compatibility) tb = [tuple(fs) for fs in traceback.extract_tb(trace)] title = traceback.format_exception_only(extype, exvalue)[0] # send an Exception notification msg = {'method': 'exception', 'args': (title, extype.__name__, repr(exvalue), tb, msg), 'id': None} self.pipe.send(msg) self.interaction(frame)
def _worker_run_collect(all_args): try: collect_once, counter, lock, threshold, args = all_args collected = [] while True: with lock: if counter.value >= threshold: return collected result, inc = collect_once(singleton_pool.G, *args) collected.append(result) with lock: counter.value += inc if counter.value >= threshold: return collected except Exception: raise Exception("".join(traceback.format_exception(*sys.exc_info())))
def generic(context, request): settings = request.registry.settings with JSONAPIResponse(request.response) as resp: _in = u'Failed' code, status = JSONAPIResponse.INTERNAL_SERVER_ERROR request.response.status_int = code try: message = {'message': context.args[0]} except IndexError: message = {'message': 'Unknown error'} if settings.get('baka.debug', True): message['traceback'] = ''.join( traceback.format_exception(*request.exc_info)) return resp.to_json( _in, code=code, status=status, message=message)
def __exit__(self, exec_type, exec_value, trace): self.body_executed = True retval = False # SystemExit is ignored to properly handle forks that don't exec if exec_type in (None, SystemExit): return retval elif exec_type is errors.SignalExit: logger.debug("Encountered signals: %s", self.received_signals) retval = True else: logger.debug("Encountered exception:\n%s", "".join( traceback.format_exception(exec_type, exec_value, trace))) self._call_registered() self._reset_signal_handlers() self._call_signals() return retval
def checkListenTask(self): self.listener.unschedule_all() if self.listenDirEnableFlag.get(): print("enable") listen_dir = os.path.abspath(self.listenDirPath.get()) try: self.listener.schedule(self._listen_handler, listen_dir, recursive = True) except Exception as e: messagebox.showinfo("listen dir {dirname} failed" .format(dirname = listen_dir), "{reason}".format( reason = traceback.format_exception(*sys.exc_info()) ) ) else: print("disable")
def update_with_translator(self, canonical_ref, dataset_iterator): translator = dataset_iterator.translator translator_info = { 'id': unicode(translator.versioned_id()), } result = next(dataset_iterator) translated = result['translated'] raw = result['raw_content'] local_assets = result.get('local_assets', {}) try: refs = self.submit_translator_output( translator_info, translated, raw, local_assets, existing_canonical_ref=multihash_ref(canonical_ref)) return refs except AbortionError: for line in traceback.format_exception(*sys.exc_info()): print_err(line.rstrip('\n'))
def write_dataset(self, dataset_iterator): translator = dataset_iterator.translator translator_info = { 'id': translator.versioned_id(), } try: translator_info['link'] = multihash_ref( translator.__version__).to_map() except (ValueError, TypeError): pass for result in dataset_iterator: translated = result['translated'] raw = result['raw_content'] local_assets = result.get('local_assets', {}) try: refs = self.submit_translator_output(translator_info, translated, raw, local_assets) yield refs except AbortionError: for line in traceback.format_exception(*sys.exc_info()): print_err(line.rstrip('\n'))
def handle_exception(self, exception, debug_mode): """Called if this handler throws an exception during execution. The default behavior is to call self.error(500) and print a stack trace if debug_mode is True. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode """ self.error(500) logging.exception(exception) if debug_mode: lines = ''.join(traceback.format_exception(*sys.exc_info())) self.response.clear() self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True)))
def on_command_error(ctx, error): if isinstance(error, commands.errors.CommandNotFound): pass if isinstance(error, commands.errors.CheckFailure): await ctx.send("{} You don't have permission to use this command.".format(ctx.message.author.mention)) elif isinstance(error, commands.errors.MissingRequiredArgument): formatter = commands.formatter.HelpFormatter() msg = await formatter.format_help_for(ctx, ctx.command) await ctx.send("{} You are missing required arguments.\n{}".format(ctx.message.author.mention, msg[0])) elif isinstance(error, commands.errors.CommandOnCooldown): try: await ctx.message.delete() except discord.errors.NotFound: pass message = await ctx.message.channel.send("{} This command was used {:.2f}s ago and is on cooldown. Try again in {:.2f}s.".format(ctx.message.author.mention, error.cooldown.per - error.retry_after, error.retry_after)) await asyncio.sleep(10) await message.delete() else: await ctx.send("An error occured while processing the `{}` command.".format(ctx.command.name)) print('Ignoring exception in command {0.command} in {0.message.channel}'.format(ctx)) botdev_msg = "Exception occured in `{0.command}` in {0.message.channel.mention}".format(ctx) tb = traceback.format_exception(type(error), error, error.__traceback__) print(''.join(tb)) await bot.botdev_channel.send(botdev_msg + '\n```' + ''.join(tb) + '\n```')
def format_error(e): # errback automatically wraps everything in a Twisted Failure if isinstance(e, failure.Failure): e = e.value if isinstance(e, str): err_string = e elif six.PY2: err_string = traceback.format_exc(e).rstrip() else: err_string = ''.join(traceback.format_exception(type(e), e, e.__traceback__)).rstrip() if err_string == 'None': # Reasonable heuristic for exceptions that were created by hand last = traceback.format_stack()[-2] err_string = '{}\n {}'.format(e, last) # Quick and dirty hack for now. err_string = err_string.replace('Connection to the other side was lost in a non-clean fashion', 'Connection to the other side was lost in a non-clean fashion (HINT: this generally actually means we got a connection refused error. Check that the remote is actually running.)') return error.Error(err_string)
def octario_excepthook(exc_type, exc_value, exc_traceback): """exception hook that sends OctarioException to log and other exceptions to stderr (default excepthook) """ from octario.lib.exceptions import OctarioException # sends full exception with trace to log if not isinstance(exc_value, OctarioException): return sys.__excepthook__(exc_type, exc_value, exc_traceback) if LOG.getEffectiveLevel() <= logging.DEBUG: formated_exception = "".join( traceback.format_exception(exc_type, exc_value, exc_traceback)) LOG.error(formated_exception + exc_value.message) else: LOG.error(exc_value.message)
def ssh_exec_live(ssh, cmd, timeout=None, check_retcode=True): LOG.debug(u"{}Calling SSH live: '{}'{}".format(Style.DIM, cmd, Style.RESET_ALL)) try: interact = SSHClientInteraction(ssh, timeout=timeout, display=True, logger=logging.getLogger()) interact.expect('.*') interact.send(cmd + "; exit $?") # needed to not depend on prompt type interact.tail() ret_code = interact.channel.recv_exit_status() except Exception: LOG.debug("Something went wrong in 'ssh_exec_live':\n{}".format( format_exception(sys.exc_info()) )) raise _proceed_exec_result("", "", ret_code, check_retcode) return ret_code, "", ""
def test_logging(caplog): exc1 = get_exc(raiser1) exc2 = get_exc(raiser2) m = MultiError([exc1, exc2]) message = "test test test" try: raise m except MultiError as exc: logging.getLogger().exception(message) # Join lines together formatted = "".join( format_exception(type(exc), exc, exc.__traceback__) ) assert message in caplog.text assert formatted in caplog.text
def user_exception(self, frame, info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile or self._wait_for_breakpoint: return extype, exvalue, trace = info # pre-process stack trace as it isn't pickeable (cannot be sent pure) msg = ''.join(traceback.format_exception(extype, exvalue, trace)) trace = traceback.extract_tb(trace) title = traceback.format_exception_only(extype, exvalue)[0] # send an Exception notification msg = {'method': 'exception', 'args': (title, extype.__name__, exvalue, trace, msg), 'id': None} self.pipe.send(msg) self.interaction(frame, info)
def findvideos(data): logger.info("[servertools.py] findvideos") encontrados = set() devuelve = [] # Ejecuta el findvideos en cada servidor for serverid in ALL_SERVERS: try: exec "from servers import "+serverid exec "devuelve.extend("+serverid+".find_videos(data))" except ImportError: logger.info("No existe conector para "+serverid) except: logger.info("Error en el conector "+serverid) import traceback,sys from pprint import pprint exc_type, exc_value, exc_tb = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_tb) for line in lines: line_splits = line.split("\n") for line_split in line_splits: logger.error(line_split) return devuelve
def format_message(self, message): now = datetime.datetime.utcnow() timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z" return_json = { "logger": message.name, "line_number": message.lineno, "path_name": message.pathname, "log_level": message.levelname, "type": self.logzio_type, "message": message.getMessage(), "@timestamp": timestamp } if message.exc_info: return_json["exception"] = self.format_exception(message.exc_info) else: formatted_message = self.format(message) if isinstance(formatted_message, dict): return_json.update(formatted_message) else: return_json["message"] = formatted_message return return_json
def render_POST(self, request): """ Handle a request from the client. """ script_env = { method: api_method(request, method) for method in request.sdata.api.fns } # Make get do auto-formatting for convenience, even though this # breaks if you try to use literal '{}' named arguments # @@@ reconsider whether this is at all a good idea def get_with_formatting(path, *args): return api_method(request, 'get')(path.format(*args)) script_env['get'] = get_with_formatting script_env['re'] = re script_env['dumps'] = dumps script_env['defaultdict'] = defaultdict script_env['OrderedDict'] = OrderedDict buf = [] def dummy_print(*args): if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], dict)): buf.append(dumps(args[0], indent=4)) else: buf.append(' '.join(map(str, args))) script_env['print'] = dummy_print def run_script(script): try: exec script in script_env except: exception_info = sys.exc_info() buf.extend(traceback.format_exception(*exception_info)) request.sdata.log('got reply {}'.format(buf)) request.sdata.add_to_push_queue('script', text=dumps(buf)) script = request.args['script'][0] reactor.callInThread(run_script, script)
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) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines)
def addpackage(sitedir, name, known_paths): """Process a .pth file within the site-packages directory: For each line in the file, either combine it with sitedir to a path and add that to known_paths, or execute it if it starts with 'import '. """ if known_paths is None: _init_pathinfo() reset = 1 else: reset = 0 fullname = os.path.join(sitedir, name) try: f = open(fullname, "rU") except IOError: return with f: for n, line in enumerate(f): if line.startswith("#"): continue try: if line.startswith(("import ", "import\t")): exec line continue line = line.rstrip() dir, dircase = makepath(sitedir, line) if not dircase in known_paths and os.path.exists(dir): sys.path.append(dir) known_paths.add(dircase) except Exception as err: print >>sys.stderr, "Error processing line {:d} of {}:\n".format( n+1, fullname) for record in traceback.format_exception(*sys.exc_info()): for line in record.splitlines(): print >>sys.stderr, ' '+line print >>sys.stderr, "\nRemainder of file ignored" break if reset: known_paths = None return known_paths
def handle(self, info=None): info = info or sys.exc_info() if self.format == "html": self.file.write(reset()) formatter = (self.format=="html") and html or text plain = False try: doc = formatter(info, self.context) except: # just in case something goes wrong doc = ''.join(traceback.format_exception(*info)) plain = True if self.display: if plain: doc = doc.replace('&', '&').replace('<', '<') self.file.write('<pre>' + doc + '</pre>\n') else: self.file.write(doc + '\n') else: self.file.write('<p>A problem occurred in a Python script.\n') if self.logdir is not None: suffix = ['.txt', '.html'][self.format=="html"] (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir) try: file = os.fdopen(fd, 'w') file.write(doc) file.close() msg = '<p> %s contains the description of this error.' % path except: msg = '<p> Tried to save traceback to %s, but failed.' % path self.file.write(msg + '\n') try: self.file.flush() except: pass
def setup(level=logging.WARNING, outputs=[output.STDERR], program_name=None, capture_warnings=True): """Setup Python logging. This will setup basic handlers for Python logging. :param level: Root log level. :param outputs: Iterable of outputs to log to. :param program_name: The name of the program. Auto-detected if not set. :param capture_warnings: Capture warnings from the `warnings' module. """ root_logger = logging.getLogger(None) # Remove all handlers for handler in list(root_logger.handlers): root_logger.removeHandler(handler) # Add configured handlers for out in outputs: if isinstance(out, str): out = output.preconfigured.get(out) if out is None: raise RuntimeError("Output {} is not available".format(out)) out.add_to_logger(root_logger) root_logger.setLevel(level) program_logger = logging.getLogger(program_name) def logging_excepthook(exc_type, value, tb): program_logger.critical( "".join(traceback.format_exception(exc_type, value, tb))) sys.excepthook = logging_excepthook if capture_warnings: logging.captureWarnings(True)
def exception(self, message=None): "Log an exception as an error and debug if we're doing that." extype, ex, tb = sys.exc_info() message = "Exception: %s%s%s" % ( message + ': ' if message is not None else '', ''.join(traceback.format_exception_only(extype, ex)), ''.join(traceback.format_exception(extype, ex, tb)).strip() ) if self.forced_debug: self.debug(message) else: self.error(message) # Forced setting of debug level
def formatException(exctype, value, tb, skip=0): """Return a list of formatted exception strings. Similar to traceback.format_exception, but displays the entire stack trace rather than just the portion downstream of the point where the exception is caught. In particular, unhandled exceptions that occur during Qt signal handling do not usually show the portion of the stack that emitted the signal. """ lines = traceback.format_exception(exctype, value, tb) lines = [lines[0]] + traceback.format_stack()[:-(skip+1)] + [' --- exception caught here ---\n'] + lines[1:] return lines
def replyError(self, reqId, *exc): print("error: %s %s %s" % (self.name, str(reqId), str(exc[1]))) excStr = traceback.format_exception(*exc) try: self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=exc[1], excString=excStr)) except: self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=None, excString=excStr))