middleware.py 819 Bytes
Newer Older
1 2 3
from comment_client import CommentClientError
from django_comment_client.utils import JsonError
import json
4 5 6
import logging

log = logging.getLogger(__name__)
7

Calen Pennington committed
8 9

class AjaxExceptionMiddleware(object):
10 11 12 13
    """
    Middleware that captures CommentClientErrors during ajax requests
    and tranforms them into json responses
    """
14
    def process_exception(self, request, exception):
15 16 17 18
        """
        Processes CommentClientErrors in ajax requests. If the request is an ajax request,
        returns a http response that encodes the error as json
        """
19
        if isinstance(exception, CommentClientError) and request.is_ajax():
20 21 22 23
            try:
                return JsonError(json.loads(exception.message))
            except ValueError:
                return JsonError(exception.message)
24
        return None