HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

05-错误和异常处理(Error & Exception Handling)

第 28 / 51 段:方法 2 - HackSoft 推荐的方式

Django 风格指南 (HackSoft) · 发布 2026-02-05 · 更新 2026-11-11 · 标签:Django、错误处理、异常管理

: # 处理我们自定义的 ApplicationError if isinstance(exc, ApplicationError): data = { "message": exc.message, "extra": exc.extra } return Response(data, status=400)

# 其他未处理的异常,返回 None(会导致 500) return response

# 4. 确保响应数据有 detail 键(如果是 list 或 dict) if isinstance(exc.detail, (list, dict)): response.data = { "detail": response.data }

# 5. 转换为我们的标准格式 if isinstance(exc, exceptions.ValidationError): # 验证错误的特殊处理 response.data["message"] = "Validation error" response.data["extra"] = { "fields": response.data["detail"] } else: # 其他错误 response.data["message"] = response.data["detail"] response.data["extra"] = {}

# 6. 删除 detail 键(我们已经用 message 替换了) del response.data["detail"]

return response