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

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

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

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

方法 2 - HackSoft 推荐的方式(续)

if response is None:
    if isinstance(exc, ApplicationError):
        data = {
            "message": exc.message,
            "extra": exc.extra
        }
        return Response(data, status=400)

关键逻辑 2:ValidationError 特殊处理

if isinstance(exc, exceptions.ValidationError):
    response.data["message"] = "Validation error"
    response.data["extra"] = {
        "fields": response.data["detail"]
    }

关键逻辑 3:其他错误

else:
    response.data["message"] = response.data["detail"]
    response.data["extra"] = {}

ApplicationError 的定义