Log some exceptions

This commit is contained in:
Florian Bruhin 2014-06-20 23:26:19 +02:00
parent 736f559afa
commit 113221c731
19 changed files with 83 additions and 56 deletions

View File

@ -445,8 +445,8 @@ class Application(QApplication):
url = tab.url().toString()
if url:
pages.append(url)
except Exception: # pylint: disable=broad-except
pass
except Exception as e: # pylint: disable=broad-except
log.init.debug(e)
return pages
def _save_geometry(self):
@ -469,8 +469,8 @@ class Application(QApplication):
self._crashlogfile.close()
try:
os.remove(self._crashlogfile.name)
except PermissionError:
log.destroy.warn("Could not remove crash log!")
except PermissionError as e:
log.destroy.warn("Could not remove crash log ({})!".format(e))
def _exception_hook(self, exctype, excvalue, tb):
"""Handle uncaught python exceptions.
@ -485,7 +485,8 @@ class Application(QApplication):
try:
self.shutdown()
return
except Exception:
except Exception as e:
log.destroy.debug(e)
self.quit()
return
@ -496,33 +497,37 @@ class Application(QApplication):
try:
pages = self._recover_pages()
except Exception:
except Exception as e:
log.destroy.debug(e)
pages = []
try:
history = self.mainwindow.status.cmd.history[-5:]
except Exception:
except Exception as e:
log.destroy.debug(e)
history = []
try:
widgets = self.get_all_widgets()
except Exception:
except Exception as e:
log.destroy.debug(e)
widgets = ""
try:
objects = self.get_all_objects()
except Exception:
except Exception as e:
log.destroy.debug(e)
objects = ""
# Try to shutdown gracefully
try:
self.shutdown(do_quit=False)
except Exception:
pass
except Exception as e:
log.destroy.debug(e)
try:
self.lastWindowClosed.disconnect(self.shutdown)
except TypeError:
log.destroy.warning("Preventing shutdown failed.")
except TypeError as e:
log.destroy.warning("Preventing shutdown failed ({}).")
QApplication.closeAllWindows()
self._crashdlg = ExceptionCrashDialog(pages, history, exc, widgets,
objects)
@ -569,8 +574,8 @@ class Application(QApplication):
# for page in self._opened_urls:
# try:
# argv.remove(page)
# except ValueError:
# pass
# except ValueError as e:
# logger.destroy.debug(e)
# argv = [sys.executable] + argv + pages
# log.procs.debug("Running {} with args {} (PYTHONPATH={})".format(
# sys.executable, argv, pythonpath))
@ -629,8 +634,9 @@ class Application(QApplication):
self.mainwindow.tabs.shutdown_complete.connect(partial(
self._maybe_quit, 'tabs'))
self.mainwindow.tabs.shutdown()
except AttributeError: # mainwindow or tabs could still be None
log.destroy.warning("No mainwindow/tabs to shut down.")
except AttributeError as e: # mainwindow or tabs could still be None
log.destroy.warning("No mainwindow/tabs to shut down ({}).".format(
e))
self._maybe_quit('tabs')
# Shut down networkmanager
try:
@ -638,8 +644,9 @@ class Application(QApplication):
self.networkmanager.destroyed.connect(partial(
self._maybe_quit, 'networkmanager'))
self.networkmanager.deleteLater()
except AttributeError:
log.destroy.warning("No networkmanager to shut down.")
except AttributeError as e:
log.destroy.warning("No networkmanager to shut down ({}).".format(
e))
self._maybe_quit('networkmanager')
# Re-enable faulthandler to stdout, then remove crash log
self._destroy_crashlogfile()

View File

@ -347,7 +347,8 @@ class DownloadManager(QObject):
content_disposition = rfc6266.parse_headers(
bytes(reply.rawHeader('Content-Disposition')))
filename = content_disposition.filename_unsafe
except UnicodeDecodeError:
except UnicodeDecodeError as e:
logger.warning(e)
filename = None
else:
filename = None

View File

@ -197,7 +197,8 @@ class BrowserPage(QWebPage):
"""
try:
handler = self._extension_handlers[ext]
except KeyError:
except KeyError as e:
log.webview.warning(e)
return super().extension(ext, opt, out)
return handler(opt, out)

View File

@ -140,10 +140,10 @@ class _BaseUserscriptRunner(QObject):
"""Clean up the temporary file."""
try:
os.remove(self.filepath)
except PermissionError:
except PermissionError as e:
# NOTE: Do not replace this with "raise CommandError" as it's
# executed async.
message.error("Failed to delete tempfile...")
message.error("Failed to delete tempfile... ({})".format(e))
self.filepath = None
self.proc = None

View File

@ -170,7 +170,8 @@ class ConfigManager(QObject):
lines.append("# {}{}:".format(optname, typestr))
try:
desc = self.sections[sectname].descriptions[optname]
except KeyError:
except KeyError as e:
log.misc.debug(e)
continue
for descline in desc.splitlines():
lines += wrapper.wrap(descline)

View File

@ -30,6 +30,7 @@ from PyQt5.QtNetwork import QNetworkProxy
import qutebrowser.commands.utils as cmdutils
from qutebrowser.utils.misc import get_standard_dir
from qutebrowser.utils.log import misc as logger
class ValidationError(ValueError):
@ -155,7 +156,8 @@ class BaseType:
for val in self.valid_values:
try:
desc = self.valid_values.descriptions[val]
except KeyError:
except KeyError as e:
logger.warning(e)
desc = ""
out.append((val, desc))
return out

View File

@ -104,7 +104,8 @@ class ColorDict(dict):
"""
try:
val = super().__getitem__(key)
except KeyError:
except KeyError as e:
logger.warning(e)
return ''
if 'fg' in key.split('.'):
return 'color: {};'.format(val)

View File

@ -52,8 +52,8 @@ def maybe_leave(mode, reason=None):
"""Convenience method to leave 'mode' without exceptions."""
try:
instance().leave(mode, reason)
except ValueError:
pass
except ValueError as e:
logger.debug(e)
class ModeManager(QObject):

View File

@ -25,6 +25,7 @@ import qutebrowser.config.config as config
import qutebrowser.config.configdata as configdata
from qutebrowser.models.basecompletion import BaseCompletionModel
from qutebrowser.commands.utils import cmd_dict
from qutebrowser.utils.log import completion as logger
class SettingSectionCompletionModel(BaseCompletionModel):
@ -61,7 +62,8 @@ class SettingOptionCompletionModel(BaseCompletionModel):
for name, _ in sectdata.items():
try:
desc = sectdata.descriptions[name]
except (KeyError, AttributeError):
except (KeyError, AttributeError) as e:
logger.debug(e)
desc = ""
value = config.get(section, name, raw=True)
_valitem, _descitem, miscitem = self.new_item(cat, name, desc,
@ -75,7 +77,8 @@ class SettingOptionCompletionModel(BaseCompletionModel):
return
try:
item = self._misc_items[option]
except KeyError:
except KeyError as e:
logger.debug(e)
# changed before init
return
val = config.get(section, option, raw=True)

View File

@ -25,6 +25,7 @@ from PyQt5.QtWidgets import QApplication
import qutebrowser.config.config as config
from qutebrowser.utils.usertypes import enum
from qutebrowser.utils.log import downloads as logger
Role = enum('item', start=Qt.UserRole)
@ -79,7 +80,8 @@ class DownloadModel(QAbstractListModel):
try:
item = self.downloadmanager.downloads[index.row()]
except IndexError:
except IndexError as e:
logger.debug(e)
return QVariant()
if role == Qt.DisplayRole:
data = str(item)

View File

@ -27,7 +27,7 @@ Module attributes:
import qutebrowser
import cgi
import qutebrowser.utils.log as log
import qutebrowser.utils.log as logutils
import qutebrowser.utils.version as version
from qutebrowser.network.schemehandler import (SchemeHandler,
SpecialNetworkReply)
@ -82,11 +82,12 @@ class QuteSchemeHandler(SchemeHandler):
"""
path = request.url().path()
# An url like "qute:foo" is split as "scheme:path", not "scheme:host".
log.misc.debug("url: {}, path: {}".format(
logutils.misc.debug("url: {}, path: {}".format(
request.url().toDisplayString(), path))
try:
handler = getattr(QuteHandlers, path)
except AttributeError:
except AttributeError as e:
logutils.misc.debug(e)
data = bytes()
else:
data = handler()
@ -117,10 +118,10 @@ class QuteHandlers:
@classmethod
def log(cls):
"""Handler for qute:log. Return HTML content as bytes."""
if log.ram_handler is None:
if logutils.ram_handler is None:
text = "Log output was disabled."
else:
text = cgi.escape(log.ram_handler.dump_log())
text = cgi.escape(logutils.ram_handler.dump_log())
return _get_html('log', '<pre>{}</pre>'.format(text))
@classmethod

View File

@ -120,6 +120,7 @@ class Completer(QObject):
try:
model = self._models['value'][section][option]
except KeyError:
# No completion model for this section/option.
model = None
else:
model = self._models.get(completion_name)

View File

@ -47,10 +47,10 @@ class ExternalEditor(QObject):
os.close(self.oshandle)
try:
os.remove(self.filename)
except PermissionError:
except PermissionError as e:
# NOTE: Do not replace this with "raise CommandError" as it's
# executed async.
message.error("Failed to delete tempfile...")
message.error("Failed to delete tempfile... ({})".format(e))
def on_proc_closed(self, exitcode, exitstatus):
"""Write the editor text into the form field and clean up tempfile.

View File

@ -295,11 +295,11 @@ class Question(QObject):
self.is_aborted = True
try:
self.aborted.emit()
except TypeError:
except TypeError as e:
# FIXME
# We seem to get "pyqtSignal must be bound to a QObject, not
# 'Question' here, which makes no sense at all..."
pass
logger.debug(e)
class Timer(QTimer):

View File

@ -30,6 +30,7 @@ from PyQt5.QtWebKit import qWebKitVersion
import qutebrowser
from qutebrowser.utils.misc import read_file
from qutebrowser.utils.log import misc as logger
GPL_BOILERPLATE = """
@ -81,8 +82,8 @@ def _git_str():
try:
gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.pardir, os.path.pardir)
except NameError:
pass
except NameError as e:
logger.debug(e)
else:
commit = _git_str_subprocess(gitpath)
if commit is not None:
@ -124,8 +125,8 @@ def _release_info():
try:
with open(fn, 'r') as f:
data.append((fn, ''.join(f.readlines())))
except IOError:
pass
except IOError as e:
logger.warn(e)
return data
@ -145,7 +146,8 @@ def _module_versions():
try:
lines.append('SIP: {}'.format(
sipconfig.Configuration().sip_version_str))
except (AttributeError, TypeError):
except (AttributeError, TypeError) as e:
logger.warn(e)
lines.append('SIP: ?')
try:

View File

@ -121,8 +121,8 @@ class _CrashDialog(QDialog):
try:
self._crash_info.append(("Config",
config.instance().dump_userconfig()))
except AttributeError:
pass
except AttributeError as e:
self._crash_info.append(("Config", str(e)))
def _format_crash_info(self):
"""Format the gathered crash info to be displayed.
@ -217,8 +217,8 @@ class ExceptionCrashDialog(_CrashDialog):
try:
self._crash_info.append(("Debug log",
logutils.ram_handler.dump_log()))
except AttributeError:
pass
except AttributeError as e:
self._crash_info.append(("Debug log", str(e)))
class FatalCrashDialog(_CrashDialog):

View File

@ -34,6 +34,7 @@ from qutebrowser.widgets.tabbedbrowser import TabbedBrowser
from qutebrowser.widgets.completion import CompletionView
from qutebrowser.widgets.downloads import DownloadView
from qutebrowser.utils.usertypes import PromptMode
from qutebrowser.utils.log import init as logger
class MainWindow(QWidget):
@ -58,12 +59,14 @@ class MainWindow(QWidget):
stateconf = QCoreApplication.instance().stateconfig
geom = b64decode(stateconf['geometry']['mainwindow'],
validate=True)
except (KeyError, binascii.Error):
except (KeyError, binascii.Error) as e:
logger.warn(e)
self._set_default_geometry()
else:
try:
ok = self.restoreGeometry(geom)
except KeyError:
logger.warn(e)
self._set_default_geometry()
if not ok:
self._set_default_geometry()

View File

@ -134,8 +134,9 @@ class TabbedBrowser(TabWidget):
"""
try:
self._tabs.remove(tab)
except ValueError:
log.destroy.exception("tab {} could not be removed".format(tab))
except ValueError as e:
log.destroy.exception("tab {} could not be removed ({})".format(
tab, e))
log.destroy.debug("Tabs after removing: {}".format(self._tabs))
if not self._tabs: # all tabs shut down
log.destroy.debug("Tab shutdown complete.")
@ -198,8 +199,8 @@ class TabbedBrowser(TabWidget):
"""
try:
self.currentChanged.disconnect()
except TypeError:
pass
except TypeError as e:
log.destroy.debug(e)
tabcount = self.count()
if tabcount == 0:
log.destroy.debug("No tabs -> shutdown complete")

View File

@ -24,6 +24,7 @@ from PyQt5.QtWidgets import QTabWidget, QTabBar, QSizePolicy
from PyQt5.QtGui import QIcon, QPixmap
import qutebrowser.config.config as config
import qutebrowser.utils.log as log
from qutebrowser.config.style import set_register_stylesheet
from qutebrowser.utils.style import Style
@ -110,8 +111,8 @@ class TabWidget(QTabWidget):
try:
self.setTabPosition(position_conv[posstr])
self.tabBar().setSelectionBehaviorOnRemove(select_conv[selstr])
except KeyError:
pass
except KeyError as e:
log.init.warn(e)
@pyqtSlot(str, str)
def on_config_changed(self, section, _option):