更多想法和扩展(续)
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