import logging from django.conf import settings from django.utils import timezone from rest_framework.exceptions import APIException from rest_framework.views import exception_handler as drf_exception_handler logger = logging.getLogger(__name__) def exception_handler(exc, context): logger.exception(exc) # پاسخ پیش‌فرض DRF را دریافت می‌کنیم response = drf_exception_handler(exc, context) if response is not None: response_data = { 'success': False, 'status_code': response.status_code, 'status_message': str(exc.default_detail), 'details': exc.detail, } if isinstance(exc, APIException): try: if isinstance(exc.detail, dict): if 'code' in exc.detail: error = exc.detail['code'] else: attr = next(iter(exc.detail)) error = exc.detail[attr].code else: error = exc.detail.code or exc.code except: error = '' # if isinstance(exc.detail, str): # message = exc.detail # elif isinstance(exc.detail, dict): # if 'message' in exc.detail or 'string' in exc.detail: # message = exc.detail.get('message') or exc.detail.get('string') # else: # message = error # # else: # message = error # # response_data['message'] = message response_data['details'] = exc.detail if isinstance(exc.detail, dict) else {} response_data['details']['error'] = error response_data['details']['timestamp'] = timezone.now().isoformat() response.data = response_data return response # در فایل middleware.py from django.http import JsonResponse class ErrorMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_exception(self, request, exception): logger.exception(exception) return JsonResponse( { "success": False, "status_code": 500, "status_message": "Internal server error", "details": str(exception) if settings.DEBUG else None, }, status=500 ) from rest_framework.exceptions import APIException from rest_framework import status from django.utils.translation import gettext_lazy as _ class UnprocessableEntity(APIException): status_code = 422 default_detail = 'The request was well-formed but cannot be processed due to semantic errors.' default_code = 'unprocessable_entity' class ServiceUnavailable(APIException): status_code = status.HTTP_503_SERVICE_UNAVAILABLE default_ = _('SERVICE_UNAVAILABLE') default_code = 'service_unavailable' default_detail = 'Service Unavailable'