File size: 1,871 Bytes
38171fa db79bb2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import logging
import traceback
from django.http import JsonResponse
logger = logging.getLogger(__name__)
class ExceptionMiddleware:
"""
Middleware to catch exceptions and handle them with appropriate logging and JSON response.
"""
def __init__(self, get_response):
"""
Initializes the ExceptionMiddleware with the provided get_response function.
"""
self.get_response = get_response
def __call__(self, request):
"""
Process the request and call the next middleware or view function in the chain.
"""
response = self.get_response(request)
return response
def process_exception(self, request, exception):
"""
Called when a view function raises an exception.
"""
error_type = exception.__class__.__name__
error_message = exception.args
logger.info(f"Error Type: {error_type} | Error Message: {error_message}")
logger.debug("Request Details: %s", request.__dict__)
logger.exception(traceback.format_exc())
if isinstance(exception, KeyError):
status_code = 400
message = f"Please Add Valid Data For {error_message[0]}"
error = "BAD_REQUEST"
elif isinstance(exception, AttributeError):
status_code = 500
message = "Something Went Wrong. Please try again."
error = "SOMETHING_WENT_WRONG"
elif isinstance(exception, TypeError):
status_code = 500
message = "Something Went Wrong. Please try again."
error = "SOMETHING_WENT_WRONG"
else:
status_code = 500
message = "Something Went Wrong. Please try again."
error = "SOMETHING_WENT_WRONG"
return JsonResponse({"message": message, "error": repr(exception)}, status=status_code)
|