From 65f1a46d17cc2f09600859313eba66cab9c88b6f Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Sun, 2 Jul 2017 11:36:48 -0500 Subject: [PATCH] app: Add global error handling When a controller raises an error, the application now handles it and ensures that the proper representation is returned to the user-agent. --- src/dcow/app.py | 23 +++++++++++++++++++++++ src/dcow/templates/error.html.j2 | 5 +++++ 2 files changed, 28 insertions(+) create mode 100644 src/dcow/templates/error.html.j2 diff --git a/src/dcow/app.py b/src/dcow/app.py index 1a04d96..3a03087 100644 --- a/src/dcow/app.py +++ b/src/dcow/app.py @@ -5,8 +5,13 @@ from . import ( thumbnails, ) import functools +import logging import milla.util import os +import sys + + +log = logging.getLogger(__name__) DEFAULT_CONFIG = { @@ -53,3 +58,21 @@ class Application(milla.Application): request.want = 'xhtml' request.ResponseClass = functools.partial(base.VariedResponse, request) return request + + def handle_error(self, request): + response = request.ResponseClass() + e = sys.exc_info()[1] + err = {} + if isinstance(e, milla.HTTPRedirection): + return e + elif isinstance(e, milla.WSGIHTTPException): + response.status_int = e.code + err['code'] = getattr(e, 'errno', e.code) + err['message'] = '{}'.format(e) + else: + log.exception('An unhandled exception occurred:') + response.status_int = 500 + err['code'] = -1 + err['message'] = 'An unknown error has occurred' + response.set_payload('error.html.j2', {'error': err}) + return response diff --git a/src/dcow/templates/error.html.j2 b/src/dcow/templates/error.html.j2 new file mode 100644 index 0000000..7085193 --- /dev/null +++ b/src/dcow/templates/error.html.j2 @@ -0,0 +1,5 @@ +{% extends "base.html.j2" %} +{% block body -%} +

Error

+
{{ error.message }}
+{% endblock body -%}