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