Skip to content
This repository has been archived by the owner on Mar 16, 2020. It is now read-only.

Commit

Permalink
much better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
peterbe committed Nov 1, 2011
1 parent 036fcf7 commit 8834f88
Show file tree
Hide file tree
Showing 5 changed files with 152 additions and 1 deletion.
4 changes: 4 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ def __init__(self, database_name=None):
static_path=os.path.join(os.path.dirname(__file__), "static"),
cookie_secret=settings.COOKIE_SECRET,
debug=options.debug,
email_backend=options.debug and \
'tornado_utils.send_mail.backends.console.EmailBackend' \
or 'tornado_utils.send_mail.backends.pickle.EmailBackend',
admin_emails=settings.ADMIN_EMAILS,
ui_modules=ui_modules_map,
twitter_consumer_key=settings.TWITTER_CONSUMER_KEY,
twitter_consumer_secret=settings.TWITTER_CONSUMER_SECRET,
Expand Down
68 changes: 68 additions & 0 deletions handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import tornado.gen
from tornado.web import HTTPError
from tornado_utils.routes import route
from tornado_utils.send_mail import send_email
from tornado.escape import json_decode, json_encode
from pymongo.objectid import InvalidId, ObjectId
import utils
Expand Down Expand Up @@ -118,6 +119,73 @@ def render(self, template, **options):
options['background_image'] = background_image
return tornado.web.RequestHandler.render(self, template, **options)

def write_error(self, status_code, **kwargs):
if status_code >= 500 and not self.application.settings['debug']:
if self.application.settings['admin_emails']:
try:
self._email_exception(status_code, *kwargs['exc_info'])
except:
logging.error("Failing to email exception", exc_info=True)
else:
logging.warn("No ADMIN_EMAILS set up in settings to "
"email exception")
if self.application.settings['debug']:
super(BaseHandler, self).write_error(status_code, **kwargs)
else:
options = dict(
status_code=status_code,
err_type=kwargs['exc_info'][0],
err_value=kwargs['exc_info'][1],
err_traceback=kwargs['exc_info'][2],
)
self.render("error.html", **options)

def _email_exception(self, status_code, err_type, err_val, err_traceback):
import traceback
from cStringIO import StringIO
from pprint import pprint
out = StringIO()
subject = "%r on %s" % (err_val, self.request.path)
out.write("TRACEBACK:\n")
traceback.print_exception(err_type, err_val, err_traceback, 500, out)
traceback_formatted = out.getvalue()
#print traceback_formatted
out.write("\nREQUEST ARGUMENTS:\n")
arguments = self.request.arguments
if arguments.get('password') and arguments['password'][0]:
password = arguments['password'][0]
arguments['password'] = password[:2] + '*' * (len(password) -2)
pprint(arguments, out)
out.write("\nCOOKIES:\n")
for cookie in self.cookies:
out.write("\t%s: " % cookie)
out.write("%r\n" % self.get_secure_cookie(cookie))

out.write("\nREQUEST:\n")
for key in ('full_url', 'protocol', 'query', 'remote_ip',
'request_time', 'uri', 'version'):
out.write(" %s: " % key)
value = getattr(self.request, key)
if callable(value):
try:
value = value()
except:
pass
out.write("%r\n" % value)

out.write("\nHEADERS:\n")
pprint(dict(self.request.headers), out)
try:
send_email(self.application.settings['email_backend'],
subject,
out.getvalue(),
self.application.settings['admin_emails'][0],
self.application.settings['admin_emails'],
)
except:
logging.error("Failed to send email",
exc_info=True)


@route('/')
class HomeHandler(BaseHandler):
Expand Down
4 changes: 4 additions & 0 deletions settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@

DATABASE_NAME = 'toocool'

# complete this in your local_settings.py to get emails sent on errors
ADMIN_EMAILS = (
)

try:
from local_settings import *
except ImportError:
Expand Down
75 changes: 75 additions & 0 deletions templates/error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<html>
<head>
<title>Arse!! An error happened! ({{ status_code }})</title>
<link href='http://fonts.googleapis.com/css?family=VT323' rel='stylesheet' type='text/css'>
<style>
body {
background:#0000aa;
color:#ffffff;
font-family:'VT323', courier;
font-size:15pt;
text-align:center;
margin:100px;
}

blink {
color:yellow;
}

.neg {
background:#fff;
color:#0000aa;
padding:2px 8px;
font-weight:bold;
}

p {
margin:30px 100px;
text-align:left;
}

a,a:hover {
color:inherit;
font:inherit;
}

.menu {
text-align:center;
margin-top:50px;
}
</style>
</head>
<body>
<span class="neg">ERROR {{ status_code }} - NOT COOL!</span>

<p>
{% if status_code == 500 %}
The page you requested caused an unexpected server error. In other words,
it's not your fault. However, try restarting your computer and it will
probably solve it.
{% else %}
{% if status_code == 404 %}
The page is missing or never was written. You can wait and
see if it becomes available again,<br>or you can restart your computer.
{% else %}
{{ err_value }}<br>That's not good. Most likely this problem will
solve itself if you just restart your computer.

{% end %}

{% end %}
</p>




<p>
* Send us an e-mail to notify this and try it later.<br>

* Press CTRL+ALT+DEL to restart your computer. You will<br>
&nbsp; lose unsaved information in any programs that are running.
</p>
Press any link to continue <blink>_</blink>

</body>
</html>

0 comments on commit 8834f88

Please sign in to comment.