92 lines
2.5 KiB
Python
92 lines
2.5 KiB
Python
"""
|
|
自定义异常处理
|
|
"""
|
|
from rest_framework.views import exception_handler
|
|
from rest_framework import status
|
|
from utils.response import APIResponse
|
|
|
|
|
|
class BusinessException(Exception):
|
|
"""业务异常"""
|
|
def __init__(self, code=1, message='业务错误', status_code=status.HTTP_400_BAD_REQUEST):
|
|
self.code = code
|
|
self.message = message
|
|
self.status_code = status_code
|
|
super().__init__(message)
|
|
|
|
|
|
class ErrorCode:
|
|
"""错误码定义"""
|
|
# 通用错误 1-99
|
|
SUCCESS = 0
|
|
UNKNOWN_ERROR = 1
|
|
PARAM_ERROR = 2
|
|
NOT_FOUND = 3
|
|
PERMISSION_DENIED = 4
|
|
|
|
# 用户模块 100-199
|
|
USER_NOT_FOUND = 100
|
|
USER_DISABLED = 101
|
|
PHONE_INVALID = 102
|
|
TOKEN_EXPIRED = 103
|
|
|
|
# 设备模块 200-299
|
|
DEVICE_NOT_FOUND = 200
|
|
DEVICE_ALREADY_BOUND = 201
|
|
DEVICE_MAC_EXISTS = 202
|
|
DEVICE_SN_INVALID = 203
|
|
|
|
# 智能体模块 300-399
|
|
SPIRIT_NOT_FOUND = 300
|
|
SPIRIT_LIMIT_EXCEEDED = 301
|
|
|
|
# 批次模块 400-499
|
|
BATCH_NOT_FOUND = 400
|
|
BATCH_SN_EXISTS = 401
|
|
DEVICE_TYPE_NOT_FOUND = 402
|
|
|
|
|
|
def custom_exception_handler(exc, context):
|
|
"""自定义异常处理器"""
|
|
# 处理业务异常
|
|
if isinstance(exc, BusinessException):
|
|
return APIResponse(
|
|
code=exc.code,
|
|
message=exc.message,
|
|
status_code=exc.status_code
|
|
)
|
|
|
|
# 调用DRF默认异常处理
|
|
response = exception_handler(exc, context)
|
|
|
|
if response is not None:
|
|
# 统一格式化DRF异常
|
|
error_message = ''
|
|
if isinstance(response.data, dict):
|
|
if 'detail' in response.data:
|
|
error_message = str(response.data['detail'])
|
|
else:
|
|
# 处理字段验证错误
|
|
errors = []
|
|
for field, messages in response.data.items():
|
|
if isinstance(messages, list):
|
|
errors.append(f"{field}: {', '.join(str(m) for m in messages)}")
|
|
else:
|
|
errors.append(f"{field}: {messages}")
|
|
error_message = '; '.join(errors)
|
|
else:
|
|
error_message = str(response.data)
|
|
|
|
return APIResponse(
|
|
code=ErrorCode.UNKNOWN_ERROR,
|
|
message=error_message,
|
|
status_code=response.status_code
|
|
)
|
|
|
|
# 处理未知异常
|
|
return APIResponse(
|
|
code=ErrorCode.UNKNOWN_ERROR,
|
|
message=str(exc),
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
)
|