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

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

第 47 / 51 段:更多想法和扩展

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

更多想法和扩展(续)

5. 国际化(i18n)

from django.utils.translation import gettext as _

class ApplicationError(Exception):
    def __init__(self, message_key, extra=None):
        self.message_key = message_key
        self.message = _(message_key)  # 翻译
        self.extra = extra or {}

使用:

raise ApplicationError(
    message_key="errors.user.not_eligible",
    extra={"reason": "account_not_verified"}
)

6. 错误追踪 ID

import uuid

def exception_handler_with_tracking(exc, ctx):
    response = custom_exception_handler(exc, ctx)

    if response is not None:
        # 添加唯一的错误追踪 ID
        error_id = str(uuid.uuid4())
        response.data['error_id'] = error_id

        # 记录到日志
        logger.error(
            f"Error {error_id}: {exc}",
            exc_info=True,
            extra={'error_id': error_id}
        )

    return response

响应: