2026-02-14 16:50:02 +08:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
"""
|
2026-02-26 01:27:35 +08:00
|
|
|
|
DRF 自定义异常处理器:统一错误响应格式为 code、data、msg。
|
2026-02-14 16:50:02 +08:00
|
|
|
|
"""
|
|
|
|
|
|
from rest_framework.views import exception_handler
|
2026-02-25 00:10:04 +08:00
|
|
|
|
from rest_framework.exceptions import APIException
|
2026-02-14 16:50:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def custom_exception_handler(exc, context):
|
|
|
|
|
|
response = exception_handler(exc, context)
|
|
|
|
|
|
if response is not None:
|
2026-02-25 00:10:04 +08:00
|
|
|
|
if isinstance(exc, APIException) and getattr(exc, "status_code", None):
|
|
|
|
|
|
response.status_code = exc.status_code
|
2026-02-26 01:27:35 +08:00
|
|
|
|
code = response.status_code
|
2026-02-14 16:50:02 +08:00
|
|
|
|
if isinstance(response.data, list):
|
2026-02-26 01:27:35 +08:00
|
|
|
|
msg = response.data[0] if response.data else str(exc)
|
|
|
|
|
|
elif isinstance(response.data, dict) and "detail" in response.data:
|
|
|
|
|
|
msg = response.data["detail"]
|
|
|
|
|
|
else:
|
|
|
|
|
|
msg = str(response.data) if response.data else str(exc)
|
|
|
|
|
|
response.data = {"code": code, "data": None, "msg": msg}
|
2026-02-14 16:50:02 +08:00
|
|
|
|
return response
|