You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

电商项目Stripe测试支付异常排查:支付成功却触发严重错误提示

排查Stripe支付成功后却显示严重错误的问题

看起来你遇到了一个有点棘手的情况:明明支付完成、订单也生成了,但用户最终却收到了"A serious Error Occured. We have been notified."的错误提示。这说明在Stripe支付成功后的后续流程里,触发了一个未被Stripe相关异常捕获的错误,直接掉进了最外层的except Exception as e:分支里。

我帮你梳理几个最可能的原因和对应的排查修复步骤:

1. 邮件发送环节抛出异常

你的代码在订单保存后会发送确认邮件,这部分逻辑没有单独的异常捕获,而且msg.fail_silently = False意味着只要邮件发送失败(比如SMTP配置错误、用户邮箱格式无效、模板渲染出错等),就会直接抛出异常,触发通用错误提示。

排查&修复:

  • 先临时把fail_silently改成True,测试是否还会出现错误:
    msg.fail_silently = True  # 临时禁用发送失败抛出异常
    
    如果此时用户能正常看到成功页面,那问题肯定出在邮件发送上。
  • 给邮件逻辑单独添加异常捕获,同时记录错误日志,不影响主流程:
    # 导入logging(如果没导入的话)
    import logging
    logger = logging.getLogger(__name__)
    
    # 邮件发送部分修改为:
    try:
        template = render_to_string("payment_confirmation_email.html", {'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name, 'order': order})
        msg = EmailMessage('Thanks for Purchasing', template, settings.EMAIL_HOST_USER, [self.request.user.email])
        msg.content_subtype = "html"
        msg.fail_silently = False
        msg.send()
    except Exception as e:
        logger.error(f"Failed to send order confirmation email: {str(e)}", exc_info=True)
        messages.info(self.request, "Your order was successful! We couldn't send a confirmation email right now, but we'll follow up soon.")
    

2. create_ref_code()函数抛出异常

你在给订单设置ref_code时调用了create_ref_code(),如果这个函数内部有逻辑错误(比如依赖的库未安装、生成的代码不符合Order模型ref_code字段的要求),会在order.save()时抛出异常。

排查&修复:

  • 检查create_ref_code()的实现,确保它不会返回空值、符合字段长度要求,并且内部没有未处理的异常。比如如果ref_codeCharField(max_length=20),那函数必须返回不超过20位的字符串。
  • 在调用create_ref_code()时添加异常捕获:
    try:
        order.ref_code = create_ref_code()
    except Exception as e:
        logger.error(f"Failed to generate ref code: {str(e)}", exc_info=True)
        # 可以设置一个默认的临时参考码
        order.ref_code = f"TEMP-{order.id}"
    order.save()
    

3. 模板渲染出错

render_to_string渲染payment_confirmation_email.html时,如果模板里引用了不存在的变量(比如order的某个属性你写错了),也会抛出异常。

排查:

  • 直接在视图里测试渲染模板,看是否会报错:
    # 在post方法里临时添加(测试后删除)
    test_template = render_to_string("payment_confirmation_email.html", {'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name, 'order': order})
    print(test_template)
    
    如果打印时出错,就去检查模板里的变量引用是否正确。

通用排查技巧:记录具体错误信息

不管是什么原因,先给最外层的except Exception as e:添加日志,把具体的错误信息打出来,这样你就能精准定位问题:

except Exception as e:
    import logging
    logger = logging.getLogger(__name__)
    logger.error(f"Serious error in PaymentView post: {str(e)}", exc_info=True)  # exc_info会打印完整的堆栈信息
    messages.warning(
        self.request, "A serious Error Occured. We have been notified.")
    return redirect("/")

查看日志后,就能知道到底是哪一行代码抛出了异常。


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

火山引擎 最新活动