【发布时间】:2015-11-02 21:59:03
【问题描述】:
我的代码的简化版:
1.upto(2) do |try|
begin
puts "Start"
rescue => e
if try == 2
puts "Error - #{e}"
end
else
puts "Success"
end
end
我的问题是,当我遇到错误时,会发生这种情况:
Start
Start
Error - some message
Success
这里真的让我摸不着头脑,因为这不是应该发生的事情......有什么想法吗?
更新
好的,我认为我通过输入代码的简化版本对自己造成了伤害,因为这可行,但下面的完整版本却不行。即,当 Stripe 抛出 API 异常时,电子邮件仍在触发。
1.upto(2) do |try|
Stripe.api_key = ENV['Stripe_Secret_Key']
begin
customer = Stripe::Customer.create(
:source => params[:stripeToken],
:email => @rentalrequest.email
)
@charge = Stripe::Charge.create(
amount: (@rentalrequest.actual_amount * 100), # Stripe requires cents
currency: "usd",
customer: customer.id,
description: "Payment from #{@rentalrequest.email} for gear rental"
)
rescue => e
if try == 2
logger.fatal "Stripe error: #{e.class}, #{e.message}"
StripeErrorEmail.new.async.perform(e.class, e.message, @rentalrequest.id)
render "rental_requests/new" and return
end
else
RoadrunnerEmailAlert.new.async.perform(@rentalrequest.id)
end
end
换句话说,StripeErrorEmail 和 RoadrunnerEmailAlert 都在开火
更新 KM 的答案
def error_handle(e, id)
# Since it's a decline, Stripe::CardError will be caught
body = e.json_body
err = body[:error]
puts "Status is: #{e.http_status}"
# => 400
puts "Type is: #{err[:type]}"
# => invalid_request_error
puts "Code is: #{err[:code]}"
# => nil
puts "Param is: #{err[:param]}"
# => nil
puts "Message is: #{err[:message]}"
# => You cannot use a Stripe token more than once
logger.fatal "Stripe error: #{e.class}, #{e.message}"
StripeErrorEmail.new.async.perform(e.class, e.message, id)
render "rental_requests/new" and return
end
def charge
@rentalrequest = RentalRequest.find(params[:rentalrequest_id])
# Up to two tries
1.upto(2) do |try|
Stripe.api_key = ENV['Stripe_Secret_Key']
begin
customer = Stripe::Customer.create(
:source => params[:stripeToken],
:email => @rentalrequest.email
)
@charge = Stripe::Charge.create(
amount: (@rentalrequest.actual_amount * 100), # Stripe requires cents
currency: "usd",
customer: customer.id,
description: "Payment from #{@rentalrequest.email} for gear rental"
)
rescue Stripe::CardError => e
if try == 2
error_handle(e, @rentalrequest.id)
end
rescue Stripe::InvalidRequestError => e
if try == 2
error_handle(e, @rentalrequest.id)
end
rescue Stripe::AuthenticationError => e
if try == 2
error_handle(e, @rentalrequest.id)
end
rescue Stripe::APIConnectionError => e
if try == 2
error_handle(e, @rentalrequest.id)
end
rescue Stripe::StripeError => e
if try == 2
error_handle(e, @rentalrequest.id)
end
rescue => e
if try == 2
error_handle(e, @rentalrequest.id)
end
else
RoadrunnerEmailAlert.new.async.perform
end
end
end
【问题讨论】:
-
你有没有看到错误信息?我在本地尝试过,救援块永远不会执行,因为,没有例外。我建议你看看this post,它对 Ruby begin-rescue 流程有很好的解释。
-
您希望发生什么?
标签: ruby-on-rails ruby exception-handling stripe-payments rescue