daren/apps/template/exceptions.py
2025-05-19 18:23:59 +08:00

59 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework import status
from django.http import Http404
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from rest_framework.response import Response
def custom_exception_handler(exc, context):
"""
自定义异常处理器,将所有异常转换为标准响应格式
Args:
exc: 异常对象
context: 异常上下文
Returns:
标准格式的Response对象
"""
response = exception_handler(exc, context)
if response is not None:
# 已经被DRF处理的异常转换为标准格式
return Response({
'code': response.status_code,
'message': str(exc),
'data': response.data if hasattr(response, 'data') else None
}, status=response.status_code)
# 如果是Django的404错误
if isinstance(exc, Http404):
return Response({
'code': status.HTTP_404_NOT_FOUND,
'message': '请求的资源不存在',
'data': None
}, status=status.HTTP_404_NOT_FOUND)
# 如果是验证错误
if isinstance(exc, ValidationError):
return Response({
'code': status.HTTP_400_BAD_REQUEST,
'message': '数据验证失败',
'data': str(exc) if str(exc) else '提供的数据无效'
}, status=status.HTTP_400_BAD_REQUEST)
# 如果是数据库完整性错误(如唯一约束)
if isinstance(exc, IntegrityError):
return Response({
'code': status.HTTP_400_BAD_REQUEST,
'message': '数据库完整性错误',
'data': str(exc)
}, status=status.HTTP_400_BAD_REQUEST)
# 其他未处理的异常
return Response({
'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
'message': '服务器内部错误',
'data': str(exc) if str(exc) else None
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)