ipg/utils/exceptions.py
Sayyid Hamid Mahdavi 2ccc838b11 fallah
2025-07-29 13:23:34 +03:30

50 lines
No EOL
1.6 KiB
Python

import logging
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):
# پاسخ پیش‌فرض DRF را دریافت می‌کنیم
response = drf_exception_handler(exc, context)
if response is not None:
# ساختار دلخواه خود را تعریف می‌کنیم
response_data = {
'success': False,
'status_code': response.status_code,
'message': 'An error occurred',
'details': {}
}
if isinstance(exc, APIException):
response_data['message'] = exc.detail if isinstance(exc.detail, str) else "Validation error"
response_data['details'] = exc.detail if isinstance(exc.detail, dict) else {}
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,
"message": "Internal server error",
"details": str(exception) # فقط در حالت توسعه! در تولید بهتر است لاگ شود.
},
status=500
)