Login

Ajax error handling

Author:
kcarnold
Posted:
June 13, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.