from rest_framework.response import Response
from rest_framework import status
import json


def error_safe(function):
    def wrap(request, *args, **kwargs):
        stat = status.HTTP_500_INTERNAL_SERVER_ERROR
        try:
                return function(request, *args, **kwargs)
        # except 'DoesNotExist' as ex:
        #     print('ddd')
        #     stat = status.HTTP_404_NOT_FOUND

        except Exception as ex:
            data = ''
            try:
                data = str(ex)
                print(f'ERROR: {data}')
            except Exception as ex2:
                pass
            return Response(data={"message": data},
                            status=stat)

    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap
