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

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

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

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

更多想法和扩展(续)

from django.conf import settings

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

    # 在开发环境添加额外的调试信息
    if settings.DEBUG and response is not None:
        response.data['debug'] = {
            'exception_type': type(exc).__name__,
            'view': ctx['view'].__class__.__name__,
            'traceback': traceback.format_exc() if settings.DEBUG else None
        }

    return response

开发环境响应:

{
  "message": "Something went wrong",
  "extra": {},
  "debug": {
    "exception_type": "ValidationError",
    "view": "UserCreateApi",
    "traceback": "Traceback (most recent call last):\n..."
  }
}

4. 与 Sentry 集成

import sentry_sdk

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

    # 对于 500 错误,发送到 Sentry
    if response is None or response.status_code >= 500:
        sentry_sdk.capture_exception(exc)

    return response