Cleaned up exception logging.

This commit is contained in:
Michael Lazar
2015-10-14 23:25:50 -07:00
parent d52f574746
commit 2980097d7c
4 changed files with 20 additions and 36 deletions

View File

@@ -3,13 +3,14 @@ import sys
import locale import locale
import logging import logging
import requests
import praw import praw
import praw.errors import praw.errors
import tornado import tornado
import requests
from requests import exceptions
from . import config from . import config
from .exceptions import SubmissionError, SubredditError, SubscriptionError, ProgramError from .exceptions import RTVError
from .curses_helpers import curses_session, LoadScreen from .curses_helpers import curses_session, LoadScreen
from .submission import SubmissionPage from .submission import SubmissionPage
from .subreddit import SubredditPage from .subreddit import SubredditPage
@@ -18,6 +19,7 @@ from .oauth import OAuthTool
from .__version__ import __version__ from .__version__ import __version__
__all__ = [] __all__ = []
_logger = logging.getLogger(__name__)
# Pycharm debugging note: # Pycharm debugging note:
# You can use pycharm to debug a curses application by launching rtv in a # You can use pycharm to debug a curses application by launching rtv in a
@@ -34,10 +36,8 @@ def main():
locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, '')
# Set the terminal title # Set the terminal title
# TODO: Need to clear the title when the program exits
title = 'rtv {0}'.format(__version__) title = 'rtv {0}'.format(__version__)
if os.name == 'nt':
os.system('title {0}'.format(title))
else:
sys.stdout.write("\x1b]2;{0}\x07".format(title)) sys.stdout.write("\x1b]2;{0}\x07".format(title))
# Fill in empty arguments with config file values. Parameters explicitly # Fill in empty arguments with config file values. Parameters explicitly
@@ -54,11 +54,14 @@ def main():
config.unicode = False config.unicode = False
if not args.persistent: if not args.persistent:
config.persistent = False config.persistent = False
if args.log:
logging.basicConfig(level=logging.DEBUG, filename=args.log)
if args.clear_auth: if args.clear_auth:
config.clear_refresh_token() config.clear_refresh_token()
if args.log:
logging.basicConfig(level=logging.DEBUG, filename=args.log)
else:
logging.root.addHandler(logging.NullHandler())
try: try:
print('Connecting...') print('Connecting...')
reddit = praw.Reddit(user_agent=AGENT.format(version=__version__)) reddit = praw.Reddit(user_agent=AGENT.format(version=__version__))
@@ -74,19 +77,9 @@ def main():
subreddit = args.subreddit or 'front' subreddit = args.subreddit or 'front'
page = SubredditPage(stdscr, reddit, oauth, subreddit) page = SubredditPage(stdscr, reddit, oauth, subreddit)
page.loop() page.loop()
except (praw.errors.OAuthAppRequired, praw.errors.OAuthInvalidToken): except (exceptions.RequestException, praw.errors.PRAWException, RTVError) as e:
print('Invalid OAuth data') _logger.exception(e)
except praw.errors.NotFound: print('{}: {}'.format(type(e).__name__, e))
print('HTTP Error: 404 Not Found')
except praw.errors.HTTPException:
print('Connection timeout')
except SubmissionError as e:
print('Could not reach submission URL: {}'.format(e.url))
except SubredditError as e:
print('Could not reach subreddit: {}'.format(e.name))
except ProgramError as e:
print('Error: could not open file with program "{}", '
'try setting RTV_EDITOR'.format(e.name))
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:

View File

@@ -194,7 +194,7 @@ class SubmissionContent(BaseContent):
url = url.replace('http:', 'https:') url = url.replace('http:', 'https:')
submission = reddit.get_submission(url, comment_sort=order) submission = reddit.get_submission(url, comment_sort=order)
except (praw.errors.APIException, praw.errors.NotFound): except (praw.errors.APIException, praw.errors.NotFound):
raise SubmissionError(url) raise SubmissionError('Could not load %s' % url)
return cls(submission, loader, indent_size, max_indent_level, order) return cls(submission, loader, indent_size, max_indent_level, order)
@@ -299,7 +299,7 @@ class SubredditContent(BaseContent):
praw.errors.RedirectException, praw.errors.Forbidden, praw.errors.RedirectException, praw.errors.Forbidden,
praw.errors.InvalidSubreddit, praw.errors.NotFound, praw.errors.InvalidSubreddit, praw.errors.NotFound,
IndexError): IndexError):
raise SubredditError(name) raise SubredditError('Could not reach subreddit %s' % name)
@classmethod @classmethod
def from_name(cls, reddit, name, loader, order=None, query=None): def from_name(cls, reddit, name, loader, order=None, query=None):
@@ -317,11 +317,11 @@ class SubredditContent(BaseContent):
display_name = '/r/{}'.format(name) display_name = '/r/{}'.format(name)
if order not in ['hot', 'top', 'rising', 'new', 'controversial', None]: if order not in ['hot', 'top', 'rising', 'new', 'controversial', None]:
raise SubredditError(name) raise SubredditError('Unrecognized order "%s"' % order)
if name == 'me': if name == 'me':
if not reddit.is_logged_in(): if not reddit.is_logged_in():
raise AccountError raise AccountError('Could not access user account')
elif order: elif order:
submissions = reddit.user.get_submitted(sort=order) submissions = reddit.user.get_submitted(sort=order)
else: else:
@@ -403,7 +403,7 @@ class SubscriptionContent(BaseContent):
with loader(): with loader():
subscriptions = reddit.get_my_subreddits(limit=None) subscriptions = reddit.get_my_subreddits(limit=None)
except praw.errors.APIException: except praw.errors.APIException:
raise SubscriptionError() raise SubscriptionError('Unable to load subscriptions')
return cls(subscriptions, loader) return cls(subscriptions, loader)

View File

@@ -13,16 +13,10 @@ class AccountError(RTVError):
class SubmissionError(RTVError): class SubmissionError(RTVError):
"Submission could not be loaded" "Submission could not be loaded"
def __init__(self, url):
self.url = url
class SubredditError(RTVError): class SubredditError(RTVError):
"Subreddit could not be reached" "Subreddit could not be reached"
def __init__(self, name):
self.name = name
class SubscriptionError(RTVError): class SubscriptionError(RTVError):
"Subscriptions could not be fetched" "Subscriptions could not be fetched"
@@ -30,6 +24,3 @@ class SubscriptionError(RTVError):
class ProgramError(RTVError): class ProgramError(RTVError):
"Problem executing an external program" "Problem executing an external program"
def __init__(self, name):
self.name = name

View File

@@ -70,7 +70,7 @@ def open_editor(data=''):
try: try:
subprocess.Popen([editor, fp.name]).wait() subprocess.Popen([editor, fp.name]).wait()
except OSError: except OSError:
raise ProgramError(editor) raise ProgramError('Could not open file with %s' % editor)
curses.doupdate() curses.doupdate()
# Open a second file object to read. This appears to be necessary in # Open a second file object to read. This appears to be necessary in