web: Add top-level error handler

master
Dustin 2015-12-31 22:34:01 -06:00
parent 70e283f1c6
commit 5e72a216ed
1 changed files with 24 additions and 0 deletions

View File

@ -4,8 +4,13 @@ from milla.dispatch import routing
import functools
import jinja2
import json
import logging
import milla.util
import os
import sys
log = logging.getLogger(__name__)
class SmartJSONEncoder(json.JSONEncoder):
@ -58,6 +63,8 @@ class VariedResponse(milla.Response):
class Application(milla.Application):
ERROR_TMPL = None
def __init__(self, config=None): # pylint: disable=super-init-not-called
self.config = {}
if config and os.path.exists(config):
@ -93,3 +100,20 @@ class Application(milla.Application):
request.want = 'xhtml'
request.ResponseClass = VariedResponse.for_request(request)
return request
def handle_error(self, request):
response = request.ResponseClass()
e = sys.exc_info()[1]
context = {}
if isinstance(e, milla.HTTPRedirection):
return e
elif isinstance(e, milla.WSGIHTTPException):
log.debug('{}'.format(e))
response.status_int = e.code
context['error'] = '{}'.format(e)
else:
log.exception('An unhandled exception occurred:')
response.status_int = 500
context['error'] = 'An unknown error has occurred'
response.set_payload(self.ERROR_TMPL, context)
return response