wallet/utils/exceptions.py
2025-10-11 17:02:06 +03:30

60 lines
1.9 KiB
Python

import logging
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from django.utils.translation import gettext_lazy as _
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,
'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
)
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')