You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何使用handler500重定向到前端服务页面同时接收管理员错误邮件

Django handler500返回重定向同时触发错误邮件方案

核心原因

Django默认的管理员错误邮件仅会在响应返回500状态码时触发,自定义handler500返回302重定向响应时,会跳过默认的错误上报逻辑,因此无法收到邮件。

实现步骤

1. 自定义500错误处理视图

在项目视图文件中新增自定义handler500,手动触发错误日志上报后再返回重定向响应:

import sys
import logging
from django.shortcuts import redirect

logger = logging.getLogger('django.request')

def custom_handler500(request):
    # 手动上报错误,触发管理员邮件发送
    logger.error(
        f'Internal Server Error: {request.path}',
        exc_info=sys.exc_info(),
        extra={'status_code': 500, 'request': request}
    )
    # 替换为你的Angular前端错误页地址
    return redirect('https://your-angular-domain.com/error-path', permanent=False)

2. 绑定自定义错误处理视图

在项目根urls.py中添加配置,指定使用自定义的500错误处理器:

handler500 = 'your_project_name.views.custom_handler500'

3. 检查基础配置

确保settings.py中邮件和日志配置正确,示例参考:

# 管理员收件人配置
ADMINS = [('Admin', 'admin@example.com')]
# 发件邮箱SMTP配置
EMAIL_HOST = 'smtp.example.com'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = 'sender@example.com'
EMAIL_HOST_PASSWORD = 'your-email-password'
SERVER_EMAIL = 'sender@example.com'

注意事项

  • 重定向使用默认302临时重定向即可,不要使用301永久重定向,避免浏览器缓存导致后续正常请求被直接跳转到错误页
  • 若需要前端感知错误类型,可在重定向URL后追加查询参数,例如https://your-angular-domain.com/error?code=500,前端可根据参数展示对应提示

内容的提问来源于stack exchange,提问作者Emanuel Kozerski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:00