31 lines
1003 B
Python
31 lines
1003 B
Python
![]() |
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)
|