我正在使用 Stripe 处理订阅付款。PaymentsController
当用户输入他们的信用卡信息时,我有一个处理。Stripe 创建一个用户并将订阅附加到该用户。Stripe gem 处理这些网络请求。但是,如果 Stripe 在请求创建用户或附加订阅期间的任何时候遇到错误,我想呈现一个 json 错误。有没有办法通过 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
是的,但是您需要根据文档中此处抛出的错误类型手动处理该问题
https://stripe.com/docs/api/ruby#error_handling
您可以在任何条带错误上处理该内联的方法是将您的调用包装在 begin 块中并在救援部分返回渲染 json: 。
// 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
更一般地说,您可以将该逻辑包装在 proc 中,然后调用它,以便在返回时退出上下文。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句