Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-drf-renderer

How to store http error response in Django


I'm getting name and age and storing in the database through DRF and creating middleware that checks errors and response errors and status_code and when the middleware errors occur like 404 "Page not found, invalid URL" etc. I want to store that 'error and status_code' in the database. so how I can go through it.

Model:

class Userdata(models.Model):
name = models.CharField(max_length=150)
age = models.IntegerField()

class Errorcode(models.Model):
status_code = models.CharField(max_length=150)
message = models.CharField(max_length=300)

views:

class UserdataList(generics.ListCreateAPIView):
queryset = Userdata.objects.all()
serializer_class = UserdataSerializer

class UserdataDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Userdata
serializer_class = UserdataSerializer

class ErrorcodeList(generics.ListCreateAPIView):
queryset = Errorcode.objects.all()
serializer_class = ErrorcodeSerializer

class ErrorcodeDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Errorcode
serializer_class = ErrorcodeSerializer

Middleware:

def get_response(message="", status_code=200):
return {
   "status_code" : status_code,
   "error" : message,
}

class ExceptionMiddleware(object):
def __init__(self, get_response):
   self.get_response = get_response

def __call__(self, request):

   response = self.get_response(request)

   if response.status_code == 500:
       response = get_response(
           message="Internal server error, please try again later",
           status_code=response.status_code
       )
       return JsonResponse(response, status=response['status_code'])

   if response.status_code == 404 and "Page not found" in str(response.content):
       response = get_response(
           message="Page not found, invalid url",
           status_code=response.status_code
       )
       return JsonResponse(response, status=response['status_code'])

   return response

Solution

  • Middleware:

    def usererror(store_response):
        try:
            save_response = Errorcode.objects.create(message=str(store_response))
            save_response.save()
        except Exception as e:
            logger.error(e.__str__())
    
    
    def get_response(message, status_code):
        return {
            "status_code": status_code,
            "error": message,
        }
    
    
    class ExceptionMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
    
            response = self.get_response(request)
    
            if response.status_code == 500:
                response = get_response(
                    message="Internal server error, please try again later",
                    status_code=response.status_code
                )
                logger.error(response)
                usererror(response)
    
                return JsonResponse(response, status=response['status_code'])
    
            if response.status_code == 404 and "Page not found" in str(response.content):
                response = get_response(
                    message="Page not found, invalid url",
                    status_code=response.status_code
                )
                logger.error(response)
                usererror(response)
    
                return JsonResponse(response, status=response['status_code'])
    
            if response.status_code == 404:
                response = get_response(
                    message="Detail not found",
                    status_code=response.status_code
                )
                logger.error(response)
                usererror(response)
    
                return JsonResponse(response, status=response['status_code'])
    
            if response.status_code == 505:
                response = get_response(
                    message="HTTP version not support",
                    status_code=response.status_code
                )
                logger.error(response)
                usererror(response)
    
                return JsonResponse(response, status=response['status_code'])
    
            return response