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)