Last active
October 12, 2023 06:32
-
-
Save ridwanray/5bb12095a0f528c386681243419b2bf2 to your computer and use it in GitHub Desktop.
Custom Exception Middleware handler for django
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 | |
| from django.conf import settings | |
| from django.http import JsonResponse, HttpResponse | |
| from sentry_sdk import capture_exception | |
| class CaptureExceptionMiddleware: | |
| def __init__(self, get_response): | |
| self.get_response = get_response | |
| def __call__(self, request): | |
| return self.get_response(request) | |
| def process_exception(self, request, exception): | |
| # if exception and not settings.DEBUG: | |
| if exception: | |
| capture_exception(exception) | |
| return JsonResponse({"success": False, "error": str(exception)}, status=500) | |
| class ValidationErrorMiddleware: | |
| def __init__(self, get_response): | |
| self.get_response = get_response | |
| def __call__(self, request): | |
| response: HttpResponse = self.get_response(request) | |
| content_type = response.headers.get("Content-Type") | |
| if ( | |
| content_type | |
| and content_type == "application/json" | |
| and response.status_code == 400 | |
| ): | |
| data = json.loads(response.content) | |
| if ( | |
| isinstance(data, dict) | |
| and not data.get("detail") | |
| and not data.get("errors") | |
| ): | |
| data = {"success": False, "errors": data} | |
| response.content = json.dumps(data) | |
| return response |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MIDDLEWARE = [
"debug_toolbar.middleware.DebugToolbarMiddleware",
#.....other settings
"core.middleware.ValidationErrorMiddleware",
# "core.middleware.CaptureExceptionMiddleware",
]