haha
This commit is contained in:
@@ -1,22 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
DRF 自定义异常处理器:统一错误响应格式,并确保返回正确 HTTP 状态码。
|
||||
DRF 自定义异常处理器:统一错误响应格式为 code、data、msg。
|
||||
"""
|
||||
from rest_framework.views import exception_handler
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.exceptions import APIException
|
||||
|
||||
|
||||
def custom_exception_handler(exc, context):
|
||||
response = exception_handler(exc, context)
|
||||
if response is not None:
|
||||
# 确保使用异常自带的 HTTP 状态码(如 401 登录失效、403 无权限)
|
||||
if isinstance(exc, APIException) and getattr(exc, "status_code", None):
|
||||
response.status_code = exc.status_code
|
||||
# 统一格式:{"detail": "...", "code": 状态码}
|
||||
code = response.status_code
|
||||
if isinstance(response.data, list):
|
||||
response.data = {"detail": response.data[0] if response.data else str(exc)}
|
||||
elif isinstance(response.data, dict) and "detail" not in response.data:
|
||||
response.data = {"detail": str(response.data)}
|
||||
response.data["code"] = response.status_code
|
||||
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}
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user