I use stripe as a payment processor.
Within the application, I send a request to Stripe to execute charge or for other types of processes, and basically use the same error handling boilerplate like below.
rescue Stripe::InvalidRequestError => e,
# do something
rescue Stripe::AuthenticationError => e,
# do something
rescue Stripe::APIConnectionError => e,
# do something
rescue Stripe::StripeError => e
# do something
rescue => e
# do something
end
While I could definitely rescue each of these error types in each API call, that's a lot of boilerplate code, I'd love to just rescue on all of them, and then build a method to do things such as logging, sending notification.
How can I bundle these into one exception handler in a cleaner way (dry things up) like below?
def call
plan = Plan.new(attrs)
return plan unless plan.valid?
begin
external_card_plan_service.create(api_attrs)
rescue Exceptions::Stripe => e
plan.errors[:base] << e.message
return plan
end
plan.save
plan.update(is_active: true, activated_at: Time.now.utc)
plan
end
Not quite sure if do something is same for each case or not. If not, this might do what you want:
def handle_stripe_errors
yield
rescue Stripe::AuthenticationError => e,
# do something
rescue Stripe::APIConnectionError => e,
# do something
rescue Stripe::StripeError => e
# do something
rescue => e
# do something
end
handle_stripe_errors do
external_card_plan_service.create(api_attrs)
end
Somewhere in your app define a variable/constant/method which returns a list of the errors you want to rescue. For example:
STRIPE_ERRORS = [Stripe::InvalidRequestError, String::AuthenticationError]
The in your rescue block, you can use a splat operator to rescue any of these:
begin
<raise errors>
rescue *STRIPE_ERRORS => e
<handle errors>
end
You can check which of the errors was raised with e.class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With