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

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

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

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

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

# project/core/exceptions.py

class ApplicationError(Exception):
    """
    应用层的自定义异常
    """
    def __init__(self, message, extra=None):
        super().__init__(message)
        self.message = message
        self.extra = extra or {}

使用示例:

from project.core.exceptions import ApplicationError

def some_business_logic():
    if not user.is_eligible():
        raise ApplicationError(
            message="User is not eligible for this action",
            extra={"reason": "account_not_verified"}
        )

测试结果

仔细查看代码并尝试理解发生了什么。策略是 - 尽可能重用 DRF,然后调整。


测试 1:ApplicationError(我们的自定义异常)

代码:

from styleguide_example.core.exceptions import ApplicationError

def trigger_application_error():
    raise ApplicationError(
        message="Something is not correct",
        extra={"type": "RANDOM"}
    )

响应:

{
  "message": "Something is not correct",
  "extra": {
    "type": "RAND