诚实性修复: API限流Retry-After(wait=60s)+断言 / purge定时接线(04:00 cron+actor+测试) / Channel表单校验(ref+rules+validate) / README PG数字513
This commit is contained in:
@@ -55,9 +55,32 @@ def api_exception_handler(exc, context):
|
||||
return Response({
|
||||
"code": "server_error",
|
||||
"detail": "服务端处理异常,请稍后重试或联系管理员",
|
||||
"exc_type": type(exc).__name__,
|
||||
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
return _with_error_code(response, exc)
|
||||
|
||||
|
||||
def _with_error_code(response, exc):
|
||||
"""给"单条 detail"型错误补一个顶层 `code`,供前端判别。
|
||||
|
||||
DRF 把 code 藏在 ErrorDetail 里,序列化成纯字符串就丢了,所以
|
||||
PermissionDenied / NotAuthenticated / NotFound 这类响应到这里补回来。
|
||||
|
||||
只处理 detail 为字符串的情况:ValidationError 的 dict 形态是字段级错误,
|
||||
顶层再塞一个 `code` 会和真实字段名(如 `{"code": ["已存在"]}`)撞车。
|
||||
"""
|
||||
data = getattr(response, "data", None)
|
||||
if not isinstance(data, dict) or "code" in data:
|
||||
return response
|
||||
if not isinstance(getattr(exc, "detail", None), str):
|
||||
return response
|
||||
try:
|
||||
codes = exc.get_codes()
|
||||
except Exception: # 非 DRF 异常
|
||||
return response
|
||||
if not isinstance(codes, str):
|
||||
return response
|
||||
data["code"] = codes
|
||||
return response
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user