An exception handling middleware for Django.
- Django 2.2+ or 3.0+
- Python 3.6+
- Add
safespace
to yourINSTALLED_APPS
. - Add
safespace.middleware.SafespaceMiddleware
to yourMIDDLEWARE
orMIDDLEWARE_CLASSES
. - See below for customization.
- Raise a
safespace.excs.Problem
anywhere in your code and have it rendered as a template (or, if the request was AJAX, as JSON). - Raise any exception (that is processed by Safespace at all)
with a
response
attribute holding a DjangoHTTPResponse
to have thatresponse
returned. Useful for those exceptional cases where you just need to respond something from 50 levels deep in a call stack.
SAFESPACE_TEMPLATE_NAMES
: A list of paths to Django templates. These are actually Python.format
template strings, which will be interpolated with variables described below. As usual with lists of templates in Django, the first template to exist will be used for the rendering.SAFESPACE_TEMPLATE_ENGINE
: Which named template engine to use to render error templates. Defaults toNone
, i.e. let Django decide.SAFESPACE_EXCEPTION_CLASSES
: A list of classnames (dotted paths) to be caught by the middleware. Naturally subclasses of the given exceptions will also be caught. This defaults to processingsafespace.excs.Problem
s anddjango.core.exceptions.ValidationError
s.SAFESPACE_HTTP_STATUS
(integer): The HTTP status code for the exception responses. Defaults to "406 Not Acceptable", which may or may not be what you want, but it sure as heck is better than "200 OK" for errors.
The following variables are available for interpolation in the
SAFESPACE_TEMPLATE_NAMES
settings variable and as context in the template rendered:
{exc_type}
: The exception's class name, with CamelCase converted to snake_case. E.g.ValueError
isvalue_error
.{namespace}
: The namespace from the request's resolver match.{app_name}
: The application name from the request's resolver match.{url_name}
: The URL name from the request's resolver match.{view_name}
: The view name from the request's resolver match.{code}
: Exceptioncode
attribute, if any.{title}
: Exceptiontitle
attribute, if any.{exception}
: The exception itself. This makes no sense in interpolation.{message}
: The exception message.
In general, running tox
will test everything on every supported
platform. For development, though,
- Install development deps:
pip install -e .[dev]
- Run tests:
py.test