26 lines
802 B
Python
26 lines
802 B
Python
|
|
# exceptions.py
|
|||
|
|
from rest_framework.views import exception_handler
|
|||
|
|
from rest_framework.response import Response
|
|||
|
|
|
|||
|
|
def custom_exception_handler(exc, context):
|
|||
|
|
# 调用默认的异常处理器获取标准错误响应
|
|||
|
|
response = exception_handler(exc, context)
|
|||
|
|
|
|||
|
|
# 如果是已知的异常类型,进行统一格式化
|
|||
|
|
if response is not None:
|
|||
|
|
data = {
|
|||
|
|
'msg': str(exc) if not hasattr(exc, 'detail') else exc.detail,
|
|||
|
|
'data': None,
|
|||
|
|
'code': response.status_code
|
|||
|
|
}
|
|||
|
|
response.data = data
|
|||
|
|
else:
|
|||
|
|
# 处理未捕获的异常(比如 500)
|
|||
|
|
data = {
|
|||
|
|
'msg': 'Internal Server Error',
|
|||
|
|
'data': None,
|
|||
|
|
'code': 500
|
|||
|
|
}
|
|||
|
|
response = Response(data, status=500)
|
|||
|
|
|
|||
|
|
return response
|