Created
April 2, 2015 09:58
-
-
Save specialunderwear/1cf8b9f37feb8e9d5221 to your computer and use it in GitHub Desktop.
Django rest api exception handler, returns exceptions as json and logs exception.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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