为什么这不能正确处理我的异常?

时间:2014-03-07 01:37:25

标签: python flask stripe-payments

我正在尝试处理付款,如果付款成功或失败,需要通知客户。如果失败,我需要通知客户,并且自己也会收到错误通知,并设置烧瓶设置,以便向我发送所有错误。我想出了这个:

@app.route('/charge/',methods=['POST']) 
def charge():
    try:
      # charge payment using Stripe checkout
      ...
      ...
      # done processing      
      flash('Thanks!')
      return jsonify()
    except:
      flash("Error")
      raise

通过AJAX收到回复后,Stripe checkout会重新加载页面,以便显示我的flash消息。当事务成功后页面重新加载,我得到“谢谢!” flash消息但是当它不成功时页面仍然重新加载,但我没有收到“错误”闪存消息。

为什么?

编辑: 如果我将except更改为:

except:
      flash("Error")
      print "THIS IS PRINTING"
      raise
在抛出异常之前,

“这是打印”会在我的控制台中打印出来。 Flash重新加载时仍未显示Flash消息。

2 个答案:

答案 0 :(得分:1)

在代码中,您提到了在异常未发送回模板后发生的Flash消息,因为您没有以任何方式重新加载页面。正如前面的评论中所提到的,raise方法只是重新引发异常,而不处理它。您可以看到打印语句而不是闪存消息的原因正是这样:打印在控制台上执行,但即使执行了flash消息,也不会将其转发到任何模板。

正确的做法是:

@app.route('/charge/',methods=['POST']) 
def charge():
    try:
      # charge payment using Stripe checkout
      ...
      ...
      # done processing      
      flash('Thanks!')
      return jsonify()
    except:
      flash("Error")
      return redirect('/charge/')

另外,使用jsonify()是不正确的。它应该是:jsonify(*data to be converted, in dictionary form preferably*)

为了通过电子邮件提醒自己,您需要首先正确安装,配置和初始化电子邮件库。我假设您正在使用/可能使用Flask-mail。代码可能如下:

    @app.route('/charge/',methods=['POST']) 
    def charge():
        try:
          # charge payment using Stripe checkout
          ...
          ...
          # done processing      
          flash('Thanks!')
          return jsonify()
        except Exception as err:
          flash("Error")
          msg = Message("Hi there, you have this error:"+err+" on page '/charge/'. Jolly good!",sender="mailer@example.com", recipients=["yourself@example.com"])
          return redirect('/charge/')

答案 1 :(得分:0)

except区块中,不要重新raise例外情况;这根本不会向客户返回任何内容。你可以重定向或重新加载页面吗?在任何情况下,你都必须退货,而不是提高。