Other approach of making middleware. Advantage of is to specify, which middleware is used for which view function and in what order. Middleware function gets all arguments, that are passed to view function.
**Example usage**
@RequestMiddleware
def print_params_middleware(request, *args, **kwargs):
print 'GET params:', request.GET
@ResponseMiddleware
def modify_headers_middleware(request, response, *args, **kwargs):
response['Content-Type'] = 'text/html'
@ExceptionMiddleware
def catch_error_middleware(request, e, *args, **kwargs):
return HttpResponse('catched error %s' % e )
@modify_headers_middleware
@catch_error_middleware
@print_params_middleware
def some_view(request, *args, **kwargs):
print 'someview'
return HttpResponse()
ReportBug() allows you to send exception details to you, via email, but with
far more detail than the default. It uses the base function for the traceback
used by the Debug mode on Django.
This is a first revision, so the emails have no decent styling, but it works,
and shows scope on each stack.
It will automatically generate a random serial number per error, so you can track them
in your favourite bug tracker. It also has support for you to pass it a request variable,
so the mail would also contain request/response context. Again, i'm gonna look into doing
this manually in the future.
Hope this helps!
Mwah.
Cal Leeming.
cal [at] simplicitymedialtd.co.uk.
Simplicity Media Ltd.
A decorator that can be applied to your views to turn ObjectDoesNotExist exceptions into Http404 exceptions. This means people will see a "Page not found" error rather than an "Internal Server Error" when they are request something that does not exist in the database.
Example:
@raise_404
def show_event(request, id):
event = Event.objects.get(id)
return render_to_response('events/show_event.html', { 'event' : event })
Put this in an __init__.py somewhere that will be executed on initialization and all errors will be printed out to stderr. Useful for debugging Facebook apps, javascript calls, etc.
This is a small approach to have a middleware which automatically creates a ticket in an existing Trac environment.
**Note:** you must have the [XML-RPC-Plugin](http://trac-hacks.org/wiki/XmlRpcPlugin) installed.
Extend the attrs-dict to your needs. For example: in my case I have the SensitiveTicket-Plugin installed - automatically created tickets are marked as sensitive and are not visible to the public.
Sometimes when a Django site's authentication backend goes down, a login will fail with a 500 error. This has happened to me when using an LDAP backend for authentication. A glitch with the settings, or ldap temporarily disappearing can make logins flake out for a short period of time.
That's fine, but when a 500 error occurs it e-mails detailed information about the error to the ADMINS. We like this behavior for most errors, but it is quite frustrating when it is a login form with a password as part of a POST. If it is one of us who gets our password e-mailed out, it's even more frustrating. It hits a mailing list first, and goes to the archives to be stored in plain text. It goes to several e-mail inboxes, some of which are not local inboxes.
I decided that enough was enough. Drop this middleware in, and it will change a "password" field in the POST to twenty asterisks. This was the default way to display other sensitive settings on the DEBUG page, so I figured I'd be consistant with that.
This snippet is distributed under the GPLv3 License http://www.gnu.org/licenses/gpl-3.0-standalone.html
This exception is util when you want to raise an exception but want its message be shown as a message to the user, with no error 500 or 404 pages.
To use it, just append the middleware in the MIDDLEWARE_CLASSES setting and raises HttpMessage when necessary.
**Step 1**
Save somewhere in your project directory
**Step 2**
Add to your settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'utils.debug.UserBasedExceptionMiddleware',
)
Normal users will get your 500.html when debug = False, but If you are logged in as a super user then you get to see the stack trace in all its glory.
Handles exceptions from AJAX code, giving more useful errors and tracebacks.
(By the way, all these new snippets are extracts from [django-webapp](http://code.google.com/p/django-webapp/).)
This exact code is not well tested, but it's refactored from some code we use in production.
<code>
is_loaded = False
if not is_loaded:
is_loaded = True
#... ExceptionHandlingMiddleware as EHM
import views
EHM.append(views.AuthFailError, views.auth_fail) # when AuthFailError thrown it redirects to `auth_fail` view function.
</code>
This is another example use of the [exception middleware](http://www.djangosnippets.org/snippets/638/). It shows how to log exceptions to a file. Someone wanted to do this to avoid DOS-ing the email server in case of a silly error.
(untested.)
This exception middleware abstracts the functionality of the builtin exception handling mechanisms, but makes them extensible by inheritance.
Just add it (or some subclass) to the top of your active middleware list.
You can use this to [make your admin emails more informative](http://www.djangosnippets.org/snippets/631/) or [log errors to a file](http://www.djangosnippets.org/snippets/639/).
For PyCon we have our crash messages go to a mailman group so that people working on the site would be aware of issues. This saved us many times. But sensitive information would some times come up such as login passwords and fields we did not want going on the list.
the solution was to mask these POST fields when an exception occurs and is being handled. This is simple drop-in code which will mask the values of POST arguments which contain keywords (such as 'password', 'protected', and 'private').
Use this decorator on a function that returns a dict to get a JSON view, with error handling.
Features:
* response always includes a 'result' attribute ('ok' by default)
* catches all errors and mails the admins
* always returns JSON even on errors