middleware.py 901 Bytes
Newer Older
1
from lms.lib.comment_client import CommentClientRequestError
2 3
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
    Middleware that captures CommentClientRequestErrors during ajax requests
12 13
    and tranforms them into json responses
    """
14
    def process_exception(self, request, exception):
15
        """
16
        Processes CommentClientRequestErrors in ajax requests. If the request is an ajax request,
17 18
        returns a http response that encodes the error as json
        """
19
        if isinstance(exception, CommentClientRequestError) and request.is_ajax():
20
            try:
21
                return JsonError(json.loads(exception.message), exception.status_code)
22
            except ValueError:
23
                return JsonError(exception.message, exception.status_code)
24
        return None