【问题标题】:How to handle rendering json errors from network requests made by gems in Rails?如何处理 Rails 中 gems 发出的网络请求中呈现 json 错误?
【发布时间】:2018-09-19 15:14:05
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    是的,但您需要根据文档中此处抛出的错误类型手动处理

    https://stripe.com/docs/api/ruby#error_handling

    您可以在任何条带错误上处理该内联的方法是将您的调用包装在一个开始块中并在救援部分返回一个渲染 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 中,然后调用它,以便在返回时退出上下文。

    【讨论】:

    • 太好了,谢谢。我不确定这是特定于 API 还是可以更通用地处理,因此感谢您的彻底回复。
    猜你喜欢
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2020-10-26
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多