Simplified version of my code:
1.upto(2) do |try|
begin
puts "Start"
rescue => e
if try == 2
puts "Error - #{e}"
end
else
puts "Success"
end
end
My problem is that when I have an error, this is what happens:
Start
Start
Error - some message
Success
Really scratching my head here, because this is not what's supposed to happen... Any thoughts?
Update
OK I think I did myself a disservice by putting in the simplified version of the code, because that works, but the full version below, does not. I.e., when Stripe throws an API exception, the email is still triggering.
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
In other words, both StripeErrorEmail
and RoadrunnerEmailAlert
are firing
UPDATE for KM's answer
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