better exception

This commit is contained in:
Sayyid Hamid Mahdavi 2026-03-28 14:37:46 +03:30
parent 8f7f56f3df
commit b1867a9a07

View file

@ -10,35 +10,40 @@ def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
if response is not None:
try:
if isinstance(exc.detail, dict):
if 'code' in exc.detail:
error_code = exc.detail['code']
else:
attr = next(iter(exc.detail))
error_code = exc.detail[attr].code
else:
error_code = exc.detail.code or exc.code
except:
error_code = ''
response_data = {
'success': False,
'status_code': response.status_code,
'error_code': error_code,
'message': str(exc),
'message': str(exc.default_detail),
'details': exc.detail,
}
if isinstance(exc, APIException):
if isinstance(exc.detail, str):
message = exc.detail
elif isinstance(exc.detail, dict) and ('message' in exc.detail or 'string' in exc.detail):
message = exc.detail.get('message') or exc.detail.get('string')
else:
message = error_code
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 = ''
response_data['message'] = message
# 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 = response_data
@ -83,3 +88,4 @@ class StatusError(APIException):
status_code = status.HTTP_503_SERVICE_UNAVAILABLE
default_ = _('SERVICE_UNAVAILABLE')
default_code = 'service_unavailable'
default_detail = 'Service Unavailable'