正确处理条带错误和异常w/Ruby一次性收费

gbd*_*dev 5 ruby error-handling ruby-on-rails ruby-on-rails-3 stripe-payments

我查看了有关错误的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
Run Code Online (Sandbox Code Playgroud)

col*_*inm 13

虽然您现在可以传递闪光信息redirect_to,但您仍然可以自行操作闪光灯.

因此,对更新代码进行微小更改可让您执行所需操作:

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
Run Code Online (Sandbox Code Playgroud)

为了使您的消息更清晰,您可能希望notice在错误状态中换出alert或error闪存类型; 然后,您可以使用CSS轻松设置它们的样式,以便一目了然地指示成功或失败.(例如,Bootstrap和Foundation,每个都提供用于显示各种警报的样式.)