Handle errors

In some case it's useful to return error information to the users. But not everyone should see everything and settings.DEBUG should normally be disabled.

Here is a way to return different information to different users:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import traceback

from django.contrib import messages
from django.template import mark_safe


def lucidTag(request):
    try:
        ...do something...
    except Exception, err:
        # Base error message for all users:
        msg = u"Error doing FooBar"
        if settings.DEBUG:
            # insert more information into the traceback and re-raise the original error
            etype, evalue, etb = sys.exc_info()
            evalue = etype('%s (More info: %s)' % (msg, evalue))
            raise etype, evalue, etb

        if request.user.is_staff:
            # add more info for staff members
            msg += u" (%s)" % err
            
        if request.user.is_superuser:
            # put the full traceback into page_msg, but only for superusers
            messages.debug(request, mark_safe("%s:<pre>%s</pre>" % (msg, traceback.format_exc())))

        return u"[%s]" % msg