Reputation: 6373
I'm using Stripe to handle subscription payments. I have a PaymentsController
that handles when a user enters their credit card info. Stripe creates a user and attaches a subscription to that user. The Stripe gem handles these network requests. However, I'd like to render a json error if Stripe hits an error at any point during it's request to either create the user or attach a subscription. Is there a way to handle errors from network requests by gems?
payments_controller.rb
class Api::V1::PaymentsController < ApplicationController
before_action :authenticate_user!
def create
Stripe.api_key = ENV['STRIPE_SECRET_KEY_TEST']
// render an error if there is an issue creating a customer
customer = Stripe::Customer.create({
email: current_user.email,
source: request.params[:id]
})
stripe_plan = ENV['STRIPE_PLAN_ID_TEST']
// render an error if there is an issue creating a subscription
subscription = Stripe::Subscription.create({
customer: customer.id,
items: [{ plan: stripe_plan }],
})
current_user.subscription_plan = 1
current_user.save
if current_user.save
render json: { 'success': true }, status: 200
else
render json: { 'error': 'Some error with saving user here' }, status: 500
end
end
end
Upvotes: 0
Views: 26
Reputation: 6095
Yes, but you will need to handle that manually based on the type of error that is thrown here in the docs
https://stripe.com/docs/api/ruby#error_handling
The way you could handle that inline on any stripe error is to wrap your call in a begin block and return a render json: in the rescue portion.
// render an error if there is an issue creating a customer
begin
customer = Stripe::Customer.create({
email: current_user.email,
source: request.params[:id]
})
rescue ::Stripe::StripeError => e
render json: { 'error': 'some error'}
return
end
More generically, you could wrap that logic in a proc and then call that so that you exit the context when returning.
Upvotes: 1