62 lines
1.9 KiB
Python
62 lines
1.9 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):
|
|
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
|
|
)
|
|
|
|
|
|
from rest_framework.exceptions import APIException
|
|
|
|
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'
|