5

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

我有一个关于editPOST 到该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
4

1 回答 1

13

虽然您现在可以将 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为了使您的消息的目的更加清晰,您可能希望将错误状态换成alerterrorflash 类型;然后,您可以轻松地使用 CSS 为它们设置样式,以一目了然地指示成功或失败。(例如, BootstrapFoundation都提供了显示各种类型警报的样式。)

于 2013-10-14T04:03:01.627 回答