Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Created April 2, 2015 09:58
Show Gist options
  • Save specialunderwear/1cf8b9f37feb8e9d5221 to your computer and use it in GitHub Desktop.
Save specialunderwear/1cf8b9f37feb8e9d5221 to your computer and use it in GitHub Desktop.
Django rest api exception handler, returns exceptions as json and logs exception.
import json
import logging
import traceback
from django.http import HttpResponseServerError
from oscarapi.middleware import IsApiRequest
logger = logging.getLogger(__name__)
class JsonExceptionMiddleware(IsApiRequest):
"""
Include this middleware as the last middleware.
"""
def process_exception(self, request, exception):
if self.is_api_request(request):
strace = traceback.format_exc(exception)
logger.error(exception.message)
logger.error(strace)
return HttpResponseServerError(json.dumps({
'reason': exception.message,
'stacktrace': strace.split('\n')
}, indent=4), content_type='application/json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment