/
Codename-Nik
/
WebApp
Обзор
Документация
Войти
/
Codename-Nik
/
WebApp
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
backend/api/exceptions.py
48 строк
2 KB
Nikolay Pokhodnya
first commit
03 ноя 2025, 19:47
03 ноя 2025, 19:47
a9fbdee
Код
Авторство
О чём код?
from rest_framework.views import exception_handler from rest_framework.response import Response from rest_framework import status from django.core.exceptions import ValidationError as DjangoValidationError from django.db import IntegrityError def custom_exception_handler(exc, context): """ Custom exception handler for Django REST framework """ response = exception_handler(exc, context) if response is not None: if isinstance(response.data, dict): response.data = { 'error': True, 'message': 'Validation error', 'details': response.data } elif isinstance(response.data, list): response.data = { 'error': True, 'message': response.data[0] if response.data else 'Error occurred', 'details': {} } else: if isinstance(exc, DjangoValidationError): response = Response({ 'error': True, 'message': 'Validation error', 'details': exc.message_dict }, status=status.HTTP_400_BAD_REQUEST) elif isinstance(exc, IntegrityError): response = Response({ 'error': True, 'message': 'Database integrity error', 'details': 'The operation could not be completed due to database constraints' }, status=status.HTTP_400_BAD_REQUEST) else: response = Response({ 'error': True, 'message': 'An unexpected error occurred', 'details': str(exc) }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response