【问题标题】:Properly handling Stripe errors and exceptions w/ Ruby for one-time charge一次性使用 Ruby 正确处理 Stripe 错误和异常
【发布时间】:2013-10-21 13:46:13
【问题描述】:

我查看了Stripe documentation on errors,但在正确处理/重定向这些错误时仍然遇到一些问题。基本上无论发生什么,我都希望他们回到edit 操作(通过edit_profile_path)并向他们显示一条消息(无论成功与否)。

我有一个关于edit 操作的表单,该表单发布到update 操作。这可以使用有效的信用卡正常工作(费用在 Stripe 仪表板中)。我正在使用 Stripe.js。

class ExtrasController < ApplicationController

  def edit
    @extras = current_user.extras
  end

  def update

    Stripe.api_key = "hidden"

    token = params[:stripeToken]

    begin
      charge = Stripe::Charge.create(
        :amount => 5000, # amount in cents
        :currency => "usd",
        :card => token,
        :description => current_user.email
      )
    rescue Stripe::CardError => e
      # redirect_to edit_extras_path, notice: e.message
      # What I'm trying to do, but obviously results in AbstractController::DoubleRenderError
    rescue => e
      # Something else happened, completely unrelated to Stripe
      # Display a generic error message
    end

    redirect_to edit_extras_path, notice: "Card charged successfully."
  end

end

【问题讨论】:

  • 我建议您在有机会时将此逻辑转移到模型中。
  • 自发布此消息以来我已经这样做了。不过还是谢谢你的推荐。
  • 好人 - 我实际上将我的移动到一个专用的服务对象,因为我觉得它不适合任何模型。

标签: ruby-on-rails ruby ruby-on-rails-3 error-handling stripe-payments


【解决方案1】:

虽然您现在可以将 Flash 消息传递给 redirect_to,但您仍然可以自行操作 Flash。

因此,对更新代码进行微小的更改即可让您随心所欲:

def update

  Stripe.api_key = "hidden"

  token = params[:stripeToken]

  begin
    charge = Stripe::Charge.create(
      :amount => 5000, # amount in cents
      :currency => "usd",
      :card => token,
      :description => current_user.email
    )
    # No exceptions were raised; Set our success message.
    flash[:notice] = 'Card charged successfully.'
  rescue Stripe::CardError => e
    # CardError; display an error message.
    flash[:notice] = 'That card is presently on fire!'
  rescue => e
    # Some other error; display an error message.
    flash[:notice] = 'Some error occurred.'
  end

  redirect_to edit_extras_path
end

为了使您的消息的目的更明确,您可能希望将错误状态中的notice 替换为alerterror 闪存类型;然后,您可以轻松地使用 CSS 为它们设置样式,以一目了然地指示成功或失败。 (例如BootstrapFoundation,每个都提供了显示各种类型警报的样式。)

【讨论】:

  • 显然我对这种方式的研究太多了,哈哈。感谢您提供简单的解决方案。是的,我用alertnotice 闪光灯做到了这一点。干杯!
  • 简单的东西总是很容易被忽略!很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 2014-04-06
  • 2012-09-15
  • 2018-07-09
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多