middleware.py 902 Bytes
Newer Older
1
import json
2 3
import logging

4 5 6
from django_comment_client.utils import JsonError
from lms.lib.comment_client import CommentClientRequestError

7
log = logging.getLogger(__name__)
8

Calen Pennington committed
9 10

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