如何检查Stripe错误是否存在/是否存在Stripe错误

时间:2019-02-13 17:11:45

标签: ruby-on-rails stripe-payments

在我的Rails应用程序中,如果不存在“条带错误”,我将尝试仅运行“条带充电”命令。而且我希望能够检查Stripe错误。

charge = Stripe::Charge.create(
  :amount => amount_in_cents,
  :customer => stripe_customer,
  :description => "my application",
)

应该是这样的:

unless Stripe.errors.exists? do
   charge = Stripe::Charge.create(
      :amount => amount_in_cents,
      :customer => stripe_customer,
      :description => "my application",
   )
end

为使我的代码正常运行,我尝试puts条带错误(如果存在)。条纹错误是否是我可以puts的对象?

例如:

if Stripe.error.exists?
    puts Stripe.error
end

尝试在模型以及测试文件中使用puts命令查看输出,如下所示:

要故意创建错误:

StripeMock.prepare_card_error(:card_declined)

我正在尝试puts(但以下任何一项均无效):

puts "Stripe Card Error: #{Stripe::CardError}"

begin
  rescue Stripe::CardError => e
  body = e.json_body
  err  = body[:error]
  puts err.exists?
  puts err
end

puts err.exists?
puts err

当我尝试类似的操作时:

error = Stripe::CardError
if error
  rescue Stripe::CardError => e
end

无效,if Stripe.errorif Stripe::CardErrorif Stripe::CardError.exists?都不有效。

必须存在一些条带错误object,我们可以对其应用逻辑?!?

感谢您对puts的检查/检查“条带错误”有任何帮助。

1 个答案:

答案 0 :(得分:1)

以原始问题的注释为基础:您想捕获Stripe::charge.create()引发的异常。

begin
  puts "About to create charge"
  charge = Stripe::Charge.create(
    :amount => amount_in_cents,
    :customer => stripe_customer,
    :description => "my application",
  )
  # The next line only runs if Charge.create() did not raise an exception

  puts "Created charge #{charge.id}"
  MyDatabase.insert(charge.id)

rescue Stripe::CardError => e
  # An error was thrown, so execution of the begin block did not complete
  puts e
end

这里是a brief tutorial on exception handling in Ruby