55 lines
2.0 KiB
Python
55 lines
2.0 KiB
Python
"""
|
||
Кастомный обработчик исключений для DRF.
|
||
"""
|
||
from rest_framework.views import exception_handler
|
||
from rest_framework.response import Response
|
||
from rest_framework import status
|
||
|
||
|
||
def custom_exception_handler(exc, context):
|
||
"""
|
||
Кастомный обработчик исключений.
|
||
Возвращает ответ в унифицированном формате.
|
||
"""
|
||
# Получаем стандартный response
|
||
response = exception_handler(exc, context)
|
||
|
||
if response is not None:
|
||
# Если у исключения есть detail_dict (для PermissionDenied с дополнительными данными)
|
||
if hasattr(exc, 'detail_dict') and isinstance(exc.detail_dict, dict):
|
||
# Используем detail_dict вместо стандартного response.data
|
||
response.data = exc.detail_dict
|
||
|
||
# Форматируем ответ в унифицированный формат
|
||
custom_response_data = {
|
||
'success': False,
|
||
'error': {
|
||
'code': response.status_code,
|
||
'message': get_error_message(response.data),
|
||
'details': response.data
|
||
}
|
||
}
|
||
response.data = custom_response_data
|
||
|
||
return response
|
||
|
||
|
||
def get_error_message(data):
|
||
"""
|
||
Извлекает главное сообщение об ошибке из данных ответа.
|
||
"""
|
||
if isinstance(data, dict):
|
||
# Если есть 'detail', возвращаем его
|
||
if 'detail' in data:
|
||
return str(data['detail'])
|
||
# Иначе возвращаем первое значение
|
||
for key, value in data.items():
|
||
if isinstance(value, list) and value:
|
||
return f"{key}: {value[0]}"
|
||
return f"{key}: {value}"
|
||
elif isinstance(data, list) and data:
|
||
return str(data[0])
|
||
|
||
return 'Произошла ошибка'
|
||
|