Team Ai
Apppublic

mlnsio/text2sql

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
middleware.py56 linesDownload Raw Back to core
1import logging2import traceback3 4from django.http import JsonResponse5 6 7logger = logging.getLogger(__name__)8 9 10class ExceptionMiddleware:11    """12    Middleware to catch exceptions and handle them with appropriate logging and JSON response.13    """14 15    def __init__(self, get_response):16        """17        Initializes the ExceptionMiddleware with the provided get_response function.18        """19        self.get_response = get_response20 21    def __call__(self, request):22        """23        Process the request and call the next middleware or view function in the chain.24        """25        response = self.get_response(request)26        return response27 28    def process_exception(self, request, exception):29        """30        Called when a view function raises an exception.31        """32        error_type = exception.__class__.__name__33        error_message = exception.args34        logger.info(f"Error Type: {error_type} | Error Message: {error_message}")35        logger.debug("Request Details: %s", request.__dict__)36        logger.exception(traceback.format_exc())37 38        if isinstance(exception, KeyError):39            status_code = 40040            message = f"Please Add Valid Data For {error_message[0]}"41            error = "BAD_REQUEST"42        elif isinstance(exception, AttributeError):43            status_code = 50044            message = "Something Went Wrong. Please try again."45            error = "SOMETHING_WENT_WRONG"46        elif isinstance(exception, TypeError):47            status_code = 50048            message = "Something Went Wrong. Please try again."49            error = "SOMETHING_WENT_WRONG"50        else:51            status_code = 50052            message = "Something Went Wrong. Please try again."53            error = "SOMETHING_WENT_WRONG"54 55        return JsonResponse({"message": message, "error": repr(exception)}, status=status_code)56