From 3dd62a01734331534ae8d69d11d3eeb69e505b9a Mon Sep 17 00:00:00 2001 From: Sayyid Hamid Mahdavi Date: Sat, 25 Apr 2026 02:10:47 +0330 Subject: [PATCH] better exception --- utils/exceptions.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/utils/exceptions.py b/utils/exceptions.py index ca3ac1e..0c6dd2e 100644 --- a/utils/exceptions.py +++ b/utils/exceptions.py @@ -6,6 +6,8 @@ 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 را دریافت می‌کنیم @@ -15,8 +17,8 @@ def exception_handler(exc, context): response_data = { 'success': False, 'status_code': response.status_code, - 'status_message': str(exc.default_detail), - 'details': exc.detail, + 'status_message': str(getattr(exc, 'default_detail', exc)), + 'details': getattr(exc, 'detail', None), } if isinstance(exc, APIException): @@ -44,7 +46,10 @@ def exception_handler(exc, context): # message = error # # response_data['message'] = message - response_data['details'] = exc.detail if isinstance(exc.detail, dict) else {} + if isinstance(exc.detail, dict): + response_data['details'] = exc.detail + else: + response_data['details'] = {"message": exc.detail} response_data['details']['error'] = error response_data['details']['timestamp'] = timezone.now().isoformat() @@ -84,7 +89,7 @@ from django.utils.translation import gettext_lazy as _ class UnprocessableEntity(APIException): - status_code = status.HTTP_422_UNPROCESSABLE_ENTITY + status_code = 422 default_detail = 'The request was well-formed but cannot be processed due to semantic errors.' default_code = 'unprocessable_entity'