web: Add top-level error handler
parent
70e283f1c6
commit
5e72a216ed
|
@ -4,8 +4,13 @@ from milla.dispatch import routing
|
||||||
import functools
|
import functools
|
||||||
import jinja2
|
import jinja2
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import milla.util
|
import milla.util
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class SmartJSONEncoder(json.JSONEncoder):
|
class SmartJSONEncoder(json.JSONEncoder):
|
||||||
|
@ -58,6 +63,8 @@ class VariedResponse(milla.Response):
|
||||||
|
|
||||||
class Application(milla.Application):
|
class Application(milla.Application):
|
||||||
|
|
||||||
|
ERROR_TMPL = None
|
||||||
|
|
||||||
def __init__(self, config=None): # pylint: disable=super-init-not-called
|
def __init__(self, config=None): # pylint: disable=super-init-not-called
|
||||||
self.config = {}
|
self.config = {}
|
||||||
if config and os.path.exists(config):
|
if config and os.path.exists(config):
|
||||||
|
@ -93,3 +100,20 @@ class Application(milla.Application):
|
||||||
request.want = 'xhtml'
|
request.want = 'xhtml'
|
||||||
request.ResponseClass = VariedResponse.for_request(request)
|
request.ResponseClass = VariedResponse.for_request(request)
|
||||||
return 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
|
||||||
|
|
Loading…
Reference in New Issue