Login

Ajax error handling

Author:
kcarnold
Posted:
June 13, 2008
Language:
Python
Version:
.96
Tags:
middleware ajax error exception
Score:
1 (after 1 ratings)

Handles exceptions from AJAX code, giving more useful errors and tracebacks.

(By the way, all these new snippets are extracts from django-webapp.)

This exact code is not well tested, but it's refactored from some code we use in production.

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from django.conf import settings
from django.http import HttpResponse, Http404
from django.db.models.base import ObjectDoesNotExist
from django.utils.translation import ugettext as _

from snippet 800 import JSONEncoder
json_encode = JSONEncoder().encode

class AjaxErrorMiddleware(object):
    '''Return AJAX errors to the browser in a sensible way.

    Includes some code from http://www.djangosnippets.org/snippets/650/
    '''

    # Some useful errors that this middleware will catch.
    class InputError(Exception):
        def __init__(self, message):
            self.message = message

    class ParameterMissingError(InputError):
        def __init__(self, param):
            super(AjaxErrorMiddleware.ParameterMissingError, self).__init__(
                _('Required parameter missing: %s') % param)


    def process_exception(self, request, exception):
        if not request.is_ajax(): return

        if isinstance(exception, (ObjectDoesNotExist, Http404)):
            return self.not_found(request, exception)

        if isinstance(exception, AjaxErrorMiddleware.InputError):
            return self.bad_request(request, exception)

        return self.server_error(request, exception)
    

    def serialize_error(self, status, message):
        return HttpResponse(json_encode({
                    'status': status,
                    'message': message}),
                            status=status)

    
    def not_found(self, request, exception):
        return self.serialize_error(404, str(exception))

    
    def bad_request(self, request, exception):
        return self.serialize_error(400, exception.message)


    def server_error(self, request, exception):
        if settings.DEBUG:
            import sys, traceback
            (exc_type, exc_info, tb) = sys.exc_info()
            message = "%s\n" % exc_type.__name__
            message += "%s\n\n" % exc_info
            message += "TRACEBACK:\n"    
            for tb in traceback.format_tb(tb):
                message += "%s\n" % tb
            return self.serialize_error(500, message)
        else:
            return self.serialize_error(500, _('Internal error'))

More like this

  1. exception handling middleware by ageldama 6 years, 10 months ago
  2. Reliably create a Django File using the contents of a URL by acdha 5 years, 1 month ago
  3. Ajax form with jQuery by Donn 6 years, 6 months ago
  4. AjaxForm Base Classes by btaylordesign 3 years, 11 months ago
  5. Extensible exception handling middleware by kcarnold 6 years, 11 months ago

Comments

Please login first before commenting.