Files
boss_dp/server/core/exception_handler.py

23 lines
1.0 KiB
Python
Raw Normal View History

2026-02-14 16:50:02 +08:00
# -*- coding: utf-8 -*-
"""
2026-02-25 00:10:04 +08:00
DRF 自定义异常处理器统一错误响应格式并确保返回正确 HTTP 状态码
2026-02-14 16:50:02 +08:00
"""
from rest_framework.views import exception_handler
from rest_framework.response import Response
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
# 确保使用异常自带的 HTTP 状态码(如 401 登录失效、403 无权限)
if isinstance(exc, APIException) and getattr(exc, "status_code", None):
response.status_code = exc.status_code
2026-02-25 00:14:22 +08:00
# 统一格式:{"detail": "...", "code": 状态码}
2026-02-14 16:50:02 +08:00
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)}
2026-02-25 00:14:22 +08:00
response.data["code"] = response.status_code
2026-02-14 16:50:02 +08:00
return response