Last active
May 13, 2018 14:55
-
-
Save KaiserKatze/57ea8a3fb280c3a037700da98f900fd7 to your computer and use it in GitHub Desktop.
Django middleware, replace builtin error views with customized JsonResponse
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
| # -*- coding: utf-8 -*- | |
| from http import HTTPStatus | |
| from django.http import JsonResponse | |
| class JsonErrorMiddleware: | |
| def __init__(self, get_response): | |
| self.get_response = get_response | |
| def __call__(self, request): | |
| # Code to be executed for each request before | |
| # the view (and later middleware) are called. | |
| response = self.get_response(request) | |
| # Code to be executed for each request/response after | |
| # the view is called. | |
| status_code = response.status_code | |
| if status_code >= 400: | |
| return self.handleException(status_code) | |
| return response | |
| def handleException(self, status_code, request, response): | |
| try: | |
| status_text = HTTPStatus(status_code).phrase | |
| except KeyError: | |
| status_text = 'Unsupported Operation' | |
| return JsonResponse({ | |
| 'status_code': status_code, | |
| 'status_text': status_text, | |
| 'data': { | |
| 'request_url': request.get_full_path(), | |
| 'request_method': request.method, | |
| }, | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment