operations_project/apps/discovery/exceptions.py
2025-05-20 15:57:10 +08:00

31 lines
973 B
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.response import Response
def custom_exception_handler(exc, context):
"""
自定义异常处理
"""
# 先调用REST framework默认的异常处理方法获得标准错误响应对象
response = exception_handler(exc, context)
# 如果response为None说明REST framework无法处理该异常
# 我们依然返回None让Django处理该异常
if response is None:
return None
# 定制响应格式
error_data = {
'code': response.status_code,
'message': str(exc),
'data': None
}
# 如果是验证错误,取出错误详情
if hasattr(exc, 'detail'):
error_data['message'] = str(exc.detail)
if isinstance(exc.detail, dict):
error_data['data'] = exc.detail
# 统一返回200状态码将实际错误码放入响应体
return Response(error_data, status=200)