middleware to give json responses for exceptions
This commit is contained in:
parent
a9398240d3
commit
7c95743f5e
2 changed files with 21 additions and 4 deletions
13
oxdjango/middleware.py
Normal file
13
oxdjango/middleware.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# vi:si:et:sw=4:sts=4:ts=4
|
||||
|
||||
from shortcuts import Http404Json, render_to_json_response
|
||||
|
||||
class ExceptionMiddleware(object):
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
if isinstance(exception, Http404Json):
|
||||
return render_to_json_response(exception.response)
|
||||
else:
|
||||
return None
|
||||
|
|
@ -1,13 +1,17 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# vi:si:et:sw=4:sts=4:ts=4
|
||||
|
||||
from django.http import HttpResponse, Http404
|
||||
from django.http import HttpResponse, Http404, HttpResponseNotFound
|
||||
try:
|
||||
import simplejson
|
||||
except ImportError:
|
||||
from django.utils import simplejson
|
||||
from django.conf import settings
|
||||
|
||||
class Http404Json(Http404):
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
|
||||
def render_to_json_response(dictionary, content_type="text/json", status=200):
|
||||
indent=None
|
||||
if settings.DEBUG:
|
||||
|
@ -27,6 +31,6 @@ def get_object_or_404_json(klass, *args, **kwargs):
|
|||
return queryset.get(*args, **kwargs)
|
||||
except queryset.model.DoesNotExist:
|
||||
#FIXME: how to raise exception that will only output given result
|
||||
results = simplejson.dumps({'status': {'code': 404,
|
||||
'text': '%s not found' % queryset.model._meta.object_name}})
|
||||
raise Http404(results)
|
||||
response = {'status': {'code': 404,
|
||||
'text': '%s not found' % queryset.model._meta.object_name}}
|
||||
raise Http404Json(response)
|
||||
|
|
Loading…
Reference in a new issue