from rest_framework.exceptions import APIException
from django.http import JsonResponse
from rest_framework import status
from django.db import connection
from Rasaddam_Backend import settings
import traceback
import os


class Json500Middleware:
    """ return all 500 status errors in json response """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request, *args, **kwargs):
        try:
            return self.get_response(request)
        except Exception as exc:

            if settings.DEBUG:
                raise

            return JsonResponse({
                "message": str(exc),
                "status_code": 500,
                "error_type": exc.__class__.__name__,
                "traceback": traceback.format_exc().splitlines(),
            }, status=500)
